Let us assume that I have defined a function named computeValue (double x):
whose input is a double value
that returns a value obtained by performing a certain set of operations using the elements of an array, to be described below.
Also, we have the above mentioned array that
is some class's member
contains only 4 positions.
The 1st position contains a certain value, the 4th contains another value that will be the input to our function
(here comes the tricky bit), the 2nd and 3rd values of the array should be the result of a linear interpolation between positions 1 and 4 of the array. That is, if we modify the position 1 or 4 of the array, then positions 2 and 3 should change their values automatically according to the interpolation method.
My aim is to invoke a root-finding algorithm (such as Newton-Raphson, Secant Method, etc) that will aim to minimize the following expression:
f = CONSTANT - computeValue(array[4])
As you may have already observed, the problem is that every time my root-finding routine modifies the 4th element of my array to obtain a new solution, the positions 2 and 3 of my array should be modified accordingly given that they are the result of a interpolation (as mentioned in point 4 above), thus changing the result of computeValue.
What is a possible way of making the values of the array change dynamically as the root finding algorithm works its way towards the root? Maybe something to do with an array storing lambda expressions defining the interpolation?
It cannot be done with a classic array, but you can implement your own type that solves the problem. This type internally uses an array of length four and offers access by
public int this[int index]
{
// get and set accessors
}
Here, you can write your own getters and setters, so that you can recalculate values as soon as the others were changed.
Instead of confusing yourself with array indices, this seems like an excellent time to create your own object. You can use JF Meier's approach and manually create or augment an array class. But I suggest just creating a new object entirely. You can make your interpolated points get only properties that return the proper interpolation. Your object might look like this:
public class Interpolator
{
public double Constant {get; set;} //same as your array[0]
public double Value {get; set;} //same as your array[3]
public double Interpolation1 { get { return CalculateInterpolation1(); } }
public double Interpolation2 { get { return CalculateInterpolation2(); } }
private double CalculateInterpolation1()
{
//define your interpolation here
}
private double CalculateInterpolation2()
{
//define your interpolation here
}
}
A brief .Net Fiddle demo
Related
This question already has answers here:
What does the '=>' syntax in C# mean?
(7 answers)
Closed 2 years ago.
Please look at this block of code:
List<int> list = new List<int>();
list.Add(1);
list.Add(6);
list.Add(2);
list.Add(3);
list.Add(8);
list.Sort((x, y) => x.CompareTo(y));
int[] arr = list.ToArray();
foreach (var i in arr)
{
Console.WriteLine(i);
}
I know that when executed, the code above will print the list in ascending order. If I switch the positions of x and y in "x.CompareTo(y)", then the list will be sorted in descending order instead. I know what CompareTo() does, but here how does it work with x and y to decide the order of sorting? what does x and y represent here?
Sort method signature is public void Sort(Comparison<T> comparison), and if you see the declaration of Comparison it is public delegate int Comparison<in T>(T x, T y).
Just see the comments for Comparison.
//
// Summary:
// Represents the method that compares two objects of the same type.
//
// Parameters:
// x:
// The first object to compare.
//
// y:
// The second object to compare.
//
// Type parameters:
// T:
// The type of the objects to compare.
//
// Returns:
// A signed integer that indicates the relative values of x and y, as shown in the
// following table.
// Value – Meaning
// Less than 0 –x is less than y.
// 0 –x equals y.
// Greater than 0 –x is greater than y.
So it does the comparison for all the elements in the order, and if you swap x and y then it will do just the reverse of it.
In simple terms, (x, y) => x.CompareTo(y) is like a one line version of a method - it goes by various names, usually "lambda" or "delegate". You can think of it as a method that is stripped down as much as possible. Here's the full method, I'll talk about stripping it down shortly:
int MyComparer(int x, int y){
return x.CompareTo(y);
}
The list will perform a sort and will call this method every time it wants to make a choice as to which of the two ints it's considering, is larger than the other. How it does the sort is irrelevant, probably quicksort ish, but ultimately it will often want to know whether x is larger, same or smaller than y
You could take that method I wrote up there and call sort with it instead:
yourList.Sort(MyComparer)
So c# has this notion of being able to pass methods round in the same way that it passes variable data around. Typically when you pass a method you're saying "here's some logic you should call when you need to know that thing you want to know" - like a custom sort algorithm trhat you can vary by varying the logic you pass in
In stripping MyComparer down, well.. we know this list is full of ints so we know that x and y are ints, so we can throw the "int" away. We can get rid of the method name too, and because it's just one line we can ditch the curly brackets. The return keyword is unnecessary too because by definition to be useful the single line is going to have to evaluate to something returnable and it shall be returned implicitly. The => separates the parameters from the body logic
(method,parameters) => logic_that_produces_a_value(
So that long winded method can be boiled down to
(x,y) => x.CompareTo(y)
x,y are whatever type the list holds, the result value is a -1, 0 or 1 which list will use to determine how x and y relate sorting wise. They could be called anything; just like when you declare a method MyMethod(int left, int right) and choose to call the parameters "left" and "right", here we do the same because this is just declaring name parameters - you could easily write (left,right) => left.CompareTo(right) and it'd work the same
You'll see it a lot in c#, because c# devs are quite focused on representing logic in a compact fashion. Often the most useful way of making something flexible and powerful is to implement some of the logic but then leave it possible for another dev to finish the logic off. Microsoft implemented sorting into list, but they leave it up to us to decide "which is greater or lesser" so we can supply logic that influences sort order. They just mandated "any time we want to know which way round two things are we'll ask you" - which means they don't need to have SortAscending and SortDescending - we just flip the logic and declare that 10 is less than 9 if we want 10 to come first.
LINQ relies on "supply me some logic" heavily - you might be looking for all ints less than 3 in your list:
myList.Where(item => item < 3)
LINQ will loop over the list calling your supplied logic (lambda) here on every item and delivering only those where your lambda is true. item is one of the list entries, in this case an int. if the list held Person objects, item would be a Person. To that end I'd recommend calling it p or person to make it clearer what it is. This will become important when you start using more complex lambdas like
string[] wantedNames = new [] { "John", "Luke" };
people.Where(p => wantedNames.Any(n => p.Name == n));
This declares multiple names you're looking for then searches the list of people for all those whose name is in the list of wanted names. For every person p, LINQ asks "wantedNames, do Any of your elements return true for this supplied logic" and then it loops over the wantedNames calling the logic you supplied (n, the item from wantedNames is equal to the person name?).
Here you've used two different methods that take custom logic that LINQ calls repeatedly - Where is a method that takes a delegate, and so is Any; the Any operates on the list of names, the Where operates on the list of people so keeping it clear which is a Person p and which is a name string n using variable names is better than using bland names like a and b.
Got more into on your Sort method see the docs:
See List.Sort(Comparer) for more info
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort?view=net-5.0#System_Collections_Generic_List_1_Sort_System_Comparison__0__
I have a chunk class and I want it to contain references(represented by a int identifier) to objects that are occupying certain coordinates in the chunk. Since many objects don't have collisions, the same position may be occupied by multiple objects. The chunks have 2 dimensions (x,y). Here is what I was thinking to achieve this:
public class Chunk{
public List<int>[] objPresence;
}
This would make an array of lists( in which size = chunksizeX * chunksizeY) where the index would be the flattened x,y coordinates, and the list would contain all objects on that position. ( each int in the list would be my identifier of a given object )
So to find what objects are currently in a given position I would do:
listOfObjectsOnPosition = objPresence[ flattenIndex(x,y) ];
So far so good, but now if I want to check if one specific object is in a certain position I have to iterate through the list, and I would like to be able to have O(1) access on this.
So here is the alternative using dictionary:
public class Chunk{
public Dictionary<int,byte>[] objPresence;
}
and for access, to find a certain object:
objPresence[ flattenIndex(x,y) ].ContainsKey(objToSearch)
I can also iterate through the dictionary keys if I just want to get all objects in the position.
However in this method since I am using Dictionary, and the int key is the identifier for the object, the byte value on the dictionary is wasting memory since i dont need that value for anything.
Is there a way to implement what I have here without that wasted byte, or is there another, better way to do this altogether?
Thanks!
Our goal is to build a toy abstract syntax tree for C# classes using Roslyn. We just want to show the basic structure of a class instead of walking through the entire AST. For example (Taken from MSDN):
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
Let us only consider the Property Hours; we are only interested in extracting the tokens for modifier (public), return type (double), identifier (Hours) as for the body of two accessors we want to directly extract it as a String.
However, as we walk though the roslyn (shown in the screen dump) when we get to get accessor's body we did not find the field representing the entire string. What's the correct way of achieving this?
The obvious way is to call ToString:
Returns the string representation of this node, not including its leading and trailing trivia.
If you want the leading and trailing trivia (whitespace, comments, ...), there's ToFullString:
Returns full string representation of this node including its leading and trailing trivia.
For efficiency purposes, you may also be interested in the WriteTo method, which writes what ToFullString would produce to a TextWriter, avoiding intermediate string allocations:
Writes the full text of this node to the specified TextWriter.
Is it possible in c# to initialize an array in, for example, subindex 1?
I'm working with Office interop, and every property is an object array that starts in 1 (I assume it was originally programed in VB.NET), and you cannot modify it, you have to set the entire array for it to accept the changes.
As a workaround I am cloning the original array, modifying that one, and setting it as a whole when I'm done.
But, I was wondering if it was possible to create a new non-zero based array
It is possible to do as you request see the code below.
// Construct an array containing ints that has a length of 10 and a lower bound of 1
Array lowerBoundArray = Array.CreateInstance(typeof(int), new int[1] { 10 }, new int[1] { 1 });
// insert 1 into position 1
lowerBoundArray.SetValue(1, 1);
//insert 2 into position 2
lowerBoundArray.SetValue(2, 2);
// IndexOutOfRangeException the lower bound of the array
// is 1 and we are attempting to write into 0
lowerBoundArray.SetValue(1, 0);
You can use Array.CreateInstance.
See Array Types in .NET
Not simply. But you can certainly write your own class. It would have an array as a private variable, and the user would think his array starts at 1, but really it starts at zero and you're subtracting 1 from all of his array accesses.
You can write your own array class
I don't think if it's possible to modify the starting index of arrays.
I would create my own array using generics and handle it inside.
Just keep of const int named 'offset' with a value of one, and always add that to your subscripts in your code.
I don't think you can create non-zero based arrays in C#, but you could easily write a wrapper class of your own around the built in data structures.This wrapper class would hold a private instance of the array type you required; overloading the [] indexing operator is not allowed, but you can add an indexer to a class to make it behave like an indexable array, see here. The index function you write could then add (or subtract) 1, to all index's passed in.
You could then use your object as follows, and it would behave correctly:
myArrayObject[1]; //would return the zeroth element.
In VB6 you could change the array to start with 0 or 1, so I think VBScript can do the same. For C#, it's not possible but you can simply add NULL value in the first [0] and start real value at [1]. Of course, this is a little dangerous...
Is it possible in c# to initialize an array in, for example, subindex 1?
I'm working with Office interop, and every property is an object array that starts in 1 (I assume it was originally programed in VB.NET), and you cannot modify it, you have to set the entire array for it to accept the changes.
As a workaround I am cloning the original array, modifying that one, and setting it as a whole when I'm done.
But, I was wondering if it was possible to create a new non-zero based array
It is possible to do as you request see the code below.
// Construct an array containing ints that has a length of 10 and a lower bound of 1
Array lowerBoundArray = Array.CreateInstance(typeof(int), new int[1] { 10 }, new int[1] { 1 });
// insert 1 into position 1
lowerBoundArray.SetValue(1, 1);
//insert 2 into position 2
lowerBoundArray.SetValue(2, 2);
// IndexOutOfRangeException the lower bound of the array
// is 1 and we are attempting to write into 0
lowerBoundArray.SetValue(1, 0);
You can use Array.CreateInstance.
See Array Types in .NET
Not simply. But you can certainly write your own class. It would have an array as a private variable, and the user would think his array starts at 1, but really it starts at zero and you're subtracting 1 from all of his array accesses.
You can write your own array class
I don't think if it's possible to modify the starting index of arrays.
I would create my own array using generics and handle it inside.
Just keep of const int named 'offset' with a value of one, and always add that to your subscripts in your code.
I don't think you can create non-zero based arrays in C#, but you could easily write a wrapper class of your own around the built in data structures.This wrapper class would hold a private instance of the array type you required; overloading the [] indexing operator is not allowed, but you can add an indexer to a class to make it behave like an indexable array, see here. The index function you write could then add (or subtract) 1, to all index's passed in.
You could then use your object as follows, and it would behave correctly:
myArrayObject[1]; //would return the zeroth element.
In VB6 you could change the array to start with 0 or 1, so I think VBScript can do the same. For C#, it's not possible but you can simply add NULL value in the first [0] and start real value at [1]. Of course, this is a little dangerous...