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.
Related
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 4 years ago.
Improve this question
I have a maybe simple problem. When i start program it show "Operator '==' cannot be applied to operands of type 'string' and 'int'. I dont know what to do with it. Thanks for every help.
Here is code:
class Program
{
static bool check(string input_number)
{
for (int i = 0; i < input_number.Length / 2; i++)
if (input_number[i] != input_number[input_number.Length - i - 1])
return false;
return true;
}
static void Main(string[] args)
{
var results = from i in Enumerable.Range(100, 900)
from j in Enumerable.Range(i, 1000 - i)
let k = i * j
where (check(k.ToString() == 1)
orderby k descending
select new { i, j, k };
var highestResult = results.FirstOrDefault();
if (highestResult == null)
Console.WriteLine("There are no palindromes!");
else
Console.WriteLine($"The highest palindrome is {highestResult.i} * {highestResult.j} = {highestResult.k}");
Console.ReadKey();
}
}
You are trying to compare strings (k.ToString() with numbers (1). In your case, I think, you need to do this: where check(k.ToString()) == true).
You can't compare a string and an int directly, due to C#'s strong typing. Instead, you should "convert" the int to a string, using ToString.
edit: or just not call ToString on k?
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);
}
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 concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I wrote a little C# command application. Four arrays are supposed to be sorted with a heapsort algorithm. I took an algorithm from a website and its running just fine. Now I want to count the key-comparisons the algorithm needs to sort one array. I tried to count the comparisons via for loop but its seems to be wrong... Any ideas where I have to count for it?
Here's my sorting algorithm method. GlobalVar.CountVal is simply a public static int property.
public static void HeapSort(int[] array, int arr_ubound)
{
int i, j;
int lChild, rChild, pNode, root, temp;
root = (arr_ubound - 1) / 2;
for (j = root; j >= 0; j--)
{
for (i = root; i >= 0; i--)
{
GlobalVar.CountVal += 1;
lChild = (2*i)+1;
rChild = (2*i)+2;
if ((lChild <= arr_ubound) && (rChild <= arr_ubound))
{
if (array[rChild] >= array[lChild])
pNode = rChild;
else
pNode = lChild;
}
else
{
if (rChild > arr_ubound)
pNode = lChild;
else
pNode = rChild;
}
if (array[i] < array[pNode])
{
temp = array[i];
array[i] = array[pNode];
array[pNode] = temp;
}
}
}
temp = array[0];
array[0] = array[arr_ubound];
array[arr_ubound] = temp;
return;
}
Here's the full code: http://pastebin.com/4Y0NQECP
By using this comparer instead of the comparison operators (>= and <), you can count the comparisons properly.
public class CountingComparer<T> : Comparer<T>
{
public int Count { get; private set; }
IComparer<T> defaultComparer = Comparer<T>.Default;
public override int Compare(T left, T right)
{
this.Count++;
return defaultComparer.Compare(left, right);
}
}
To use a comparer like this, here's how you modify your code:
x [op] y // becomes
comparer.Compare(x, y) [op] 0
// e.g.
if (array[rChild] >= array[lChild]) // becomes
if (comparer.Compare(array[rChild], array[lChild]) >= 0)
Then just make sure that you use this comparer for every comparison in the heapsort (but only in that one sorting). The full code (as I ran in LINQPad) is at http://pastebin.com/UXAQh9B3. I changed your method from hardcoded to generic to more easily identify where the comparer needed to be used.
The comparison counts for your data are as follows:
1 - 652
2 - 652
3 - 0
4 - 155
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
So I'm writing a simple struct to act like an Array of strings but with some handy operators and other functions that I've always wanted to see in strings. Specifically the method I'm working on right now is the / operator. The problem is, it won't add on any remainders at the end like I want it to.
What it's supposed to do, is take an array of strings, like {"Hello", "Test1", "Test2", "Goodbye", "More?", "Qwerty"} and, say I want to divide by 4, it should return { {"Hello", "Test1", "Test2", "Goodbye"}, {"More?", "Qwerty"} } but it doesn't.
The whole class (the method I want to improve is the / operator, but if you see anything else I can work on please point it out) (I know barely any of it is commented. Sorry about that, didn't expect anyone else to see this code aside from me.):
public struct StringCollection
{
private String[] value;
public StringCollection(params String[] s)
{
this.value = s;
}
public StringCollection(StringCollection current, String ad)
{
if (current.value == null) {
current.value = new String[0] { };
}
this.value = new String[current.value.Length+1];
for (int i=0; i<this.value.Length; i++)
{
try {
this.value[i] = current[i];
} catch {
break;
}
}
this.value[this.value.Length-1] = ad;
}
public StringCollection(StringCollection x, params StringCollection[] y)
{
this.value = x.value;
for (int j=0;j<y.Length;j++)
{
for (int i=0;i<y[j].value.Length;i++)
{
this += y[j][i];
}
}
}
public static StringCollection[] operator /(StringCollection x, int y)
{
StringCollection[] result = null;
if (((int)x.value.Length/y) == ((double)x.value.Length)/y)
result = new StringCollection[y];
else
result = new StringCollection[y+1];
for (int j=0;j<y;j++)
{
for (int i=0;i<((int)x.value.Length/y);i++)
{
result[j] += x.value[i+(int)((x.value.Length/y)*j)];
}
}
if (((int)x.value.Length/y) != ((double)x.value.Length)/y)
{
// This is the part that isn't working.
for (int i=0;i<(((int)x.value.Length/y)*result[0].value.Length)-x.value.Length;i++)
{
result[result.Length-1] += x.value[i+((result[0].value.Length)*result.Length-2)];
}
}
return result;
}
public String this[int index]
{
get {
return this.value[index];
}
set {
this.value[index] = value;
}
}
}
What it does is basically takes your array (single array) and splits it into a bunch of arrays that are the same size, then it adds on the remainder in a new array at the end.
Firstly your question isn't really related to loops at all, or at least loops are only addressed in your code. You should have titled this differently.
Secondly your array adding/removing could be improved; i.e. adding 1 to array size every time and removing 1 then re-copying the entire array every time is a time-sink.
Now onto your question, your code should basically look like this:
//Make your return array
int retLen = x.Length / y;
//Add space for the remainder
if(x.Length % y != 0)
retLen++;
var ret = new StringCollection[retLen];
//Reusing variables is a good way to save memory, but watch naming conventions as this can be confusing
retLen = 0;
var tempCollection = new StringCollection();
for (int i = 0; i < x.Length; i++)
{
tempCollection = new StringCollection(tempCollection, x[i]);
if(i % y == 0 || i == x.Length - 1)
{
ret[retLen++] = tempCollection;
tempCollection = new StringCollection();
retLen = 0;
}
}
return ret;
I really don't like that you don't have a Add function in this struct, just so we're clear. the tempCollection = new StringCollection(tempCollection, x[i]); is f$*kin' TERRIBLE when it comes to time CPU time to create all those new objects.
Pretty sure you'll need to tweak that to make sure all items are entered properly, but that was a first attempt, so ... meh o.O Figured since no one was actually going to answer you I'd take the time.
EDIT: Found a bug, forgot to set retLen back to 0 when adding to ret