I have my own class using the MathDotNet package (more precisely, the Vector<double> class from namespace MathNet.Numerics.LinearAlgebra). The Vector<double> class has a method
public double At(int index)
that returns the double value of the specified index. Internally, the Vector<double> class uses a double[] for that storage. I think it is not possible to directly access the internal double[].
class TwoVectors
{
private Vector<double> v1, v2;
// initializes the vectors v1 and v2, both have length 2.
public TwoVectors(double[] entries1, double[] entries2)
{
if (entries1 == null || entries2 == null ||
entries1.Length != 2 || entries2.Length != 2)
throw new ArgumentException("Erroneous input!");
v1 = Vector<double>.Build.Dense(entries1);
v2 = Vector<double>.Build.Dense(entries2);
}
// gives a copy of the vector data.
public double[] ArrayData
{
get
{
return new double[] { v1.At(0), v1.At(1), v2.At(0), v2.At(1) };
}
}
}
But I would like the Getter not to return a copy of the vector data but the actual vector data, so that future changes are reflected in the vectors.
I.e. if I call
public static Main()
{
TwoVectors twoVec = new TwoVectors(new double[] {1, 2}, new double[] {3, 4});
twoVec.ArrayData[0] = 42;
double[] arrayData = mc.ArrayData; // this now contains {1, 2, 3, 4}
}
then I would like arrayData to contain {42, 2, 3, 4} instead of {1, 2, 3, 4}, as it does now.
I believe I can do this with pointers, but I don't know how!
I thought I could write
public double[] ArrayData
{
get
{
unsafe { return new double*[] { &v1.At(0), &v1.At(1), &v2.At(0), &v2.At(1) }; }
}
}
but the compiler tells me that the address of v1.At(0) and the other ones could not be gotten (Why?).
Also with pointers, I guess I cannot write stuff like
twoVec.ArrayData[0] = 42;
double[] arrayData = mc.ArrayData;
but something with * or & or ->, so there must be some other way... Any ideas?
PS: I know I can write an indexer for my class that looks something like this:
public double this[int i]
{
set
{
switch (i)
{
case 0: v1.At(0, value); break;
case 1: v1.At(1, value); break;
case 2: v2.At(0, value); break;
case 3: v2.At(1, value); break;
default: throw new IndexOutOfRangeException("Index must range from 0 to 3!");
}
}
}
(with method Vector<double>.At(int index, double value) being the setter counterpart to the getter method from the top of the thread)
BUT I want to know if there is a direct way to make statements like
twoVec.ArrayData[0] = 42;
work as expected (i.e. make a real change in the vectors).
Related
I am trying to solve a leetcode problem, where I want to get top k frequent numbers. I am trying to solve it using SortedSet for O(log n) time complexity.
My code is working for all inputs except one particular input.
public class FreqNode
{
public int number;
public int freq;
public FreqNode(int n, int f)
{
number = n;
freq = f;
}
}
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 3, 2, 3, 1, 2, 4, 5, 5, 6, 7, 7, 8, 2, 3, 1, 1, 1, 10, 11, 5, 6, 2, 4, 7, 8, 5, 6};
TopKFrequent(arr, 10);
Console.Read();
}
static void TopKFrequent(int[] nums, int k)
{
SortedSet<FreqNode> sl = new SortedSet<FreqNode>(new MyComparer());
Dictionary<int, FreqNode> ht = new Dictionary<int, FreqNode>();
foreach (int i in nums)
{
if (ht.ContainsKey(i))
{
sl.Remove(ht[i]);
ht[i].freq += 1;
}
else
{
ht[i] = new FreqNode(i, 1);
}
sl.Add(ht[i]);
}
for (int i = 0; i < k; i++)
{
FreqNode f = sl.ElementAt(i);
Console.WriteLine(f.number);
}
}
}
public class MyComparer : IComparer<FreqNode>
{
public int Compare(FreqNode fn1, FreqNode fn2)
{
//Remove entry with same number
//Retain entries with same frequencies.
if (fn1.number == fn2.number)
{
return 0;
}
else
{
int res = fn2.freq.CompareTo(fn1.freq);
if (res == 0)
{
return 1;
}
else
{
return res;
}
}
}
}
It prints output as - 1,2,5,3,7,6,6,4,8,10
instead of - 1,2,5,3,6,7,4,8,10,11
During debugging, I noticed that Comparer code does not compare with existing entry of number 6. After further investigation, I found that, SortedSet is implemented using Red-Black tree, but I could not resolve this bug in my code.
This problem was interesting to me because I thought it might be a SortedSet bug and had me stepping through the SortedSet source. Alas, not a SortedSet bug...sorry but your IComparer is a bit wonky.
Your IComparer implementation does weird things to the comparison by first changing the criteria of sort comparison, then by inverting the comparison objects, then by changing the return value.
First your comparer is saying,
if "number" properties are equal, the nodes are equal (this is fine)
if (fn1.number == fn2.number)
{
return 0;
}
then it's saying
sort on the inverse of the freq property (switching fn2 with fn1 is probably not a good idea, and the criteria of sort has changed to the 'freq' property (probably ok))
int res = fn2.freq.CompareTo(fn1.freq);
then it's changing equal freqs to not be equal
if the result of the 'freq' comparison was equal, let's pretend like it's not equal (probably not a good idea)
if (res == 0)
{
return 1;
}
The poor SortedSet's root must be rotating!! (HAHAHA!! I made a Data Structures joke!! get it "root"? "rotating"?)
In the end, the Remove algorithm looks for the '6' as a right child because your IComparer tells it that's where it should be, meanwhile '6' is actually a left child, so the Remove algorithm misses it.
As an aside, keep in mind that the 2 '6' nodes in your SortedSet and the '6' node in your dictionary are all actually the same FreqNode reference, so you can change all of them at the same time if you needed to.
You can look at (and download) the .NET source here
then set up Visual Studio to debug sources by following the instructions here
Lastly, if you insist solving the top-k problem this way, try this comparer:
public class MyComparer : IComparer<FreqNode>
{
public int Compare(FreqNode fn1, FreqNode fn2)
{
return fn1.number == fn2.number ? fn1.freq.CompareTo(fn2.freq) : fn1.number.CompareTo(fn2.number);
}
}
Cheers and thanks for a fun debug!
I have enum flags. How to get all combinations of flags that do not contain a specific one?
[Flags]
public enum TestEnum
{
A = 1,
B = 2,
C = 4,
D = 8
}
public static IEnumerable<Enum> AllNotContaining(this Enum value)
{....}
For example, TestEnum.A.AllNotContaining() should return {2, 4, 6, 8, 10, 12, 14}.
Step 1, use the binary NOT:
var notUsedBits = ~ value;
But this will set all of the 32 bits that were not used.
So you will probably want a mask:
[Flags]
public enum TestEnum
{
A = 1,
B = 2,
C = 4,
D = 8,
All = A|B|C|D, // or compute this inside the method
}
and then the method becomes
// untested
public static TestEnum AllNotContaining(this TestEnum value)
{
return ~ value & TestEnum.All;
}
this does not return an IEnumerable but that is weird (and inefficient) for a Flags enum anyway.
I haven't tried to polish the code below, but you should get the general idea:
public static IEnumerable<int> AllNotContaining<T>(this T value)
// where T : Enum (as of C# 7.3).
{
// Determine upper bound of values to check.
// E.g. for your test enum, the maximum value is 8 so we need to check up to 15.
var values = Enum.GetValues(typeof(T)).Cast<int>();
int max = values.Max() * 2 - 1;
// Test all values to see if the given flag is present. If not, return it.
for(int i = 0; i <= max; ++i)
{
// Possibly also: if( ((Enum)i).HasFlags(value))
if((max & Convert.ToInt32(value)) == 0)
{
yield return i;
}
}
}
Try like this:
public static IEnumerable<TestEnum> AllNotContaining(this TestEnum value)
{
return Enum.GetValues(typeof(TestEnum)).Cast<TestEnum>().Where(x => x != value).AsEnumerable();
}
Is there anyway to achieve the following in C# (or any other ,Net language)?
public double nestedParamArrayLoop(function delegatedFunction, LoopControllers loopControllers)
{
double total = 0;
NestedLoopControllers loopControllers = new NestedLoopControllers(loopController, loopMaxes);
foreach(LoopController loopController in loopControllers);
{
nestedfor (loopController)
{
// this line results in one or more loopControllers being passed in
total += delegatedFunction(loopController);
}
}
return total;
}
public double delegatedFunction(params int[] arguments)
{
// dummy function to compute product of values
long product = 1;
for (int i = 0; i < arguments.Count ; i++)
product *= arguments[i];
return product;
}
Where delegatedFunction is called with a variable number of parameters, according to the number of controllers in the array loopControllers? Each loopController would contain a start value, a max value and an increment value (i.e. template a for loop).
The syntax above doesn't quite work as I'm not sure any exists to capture this paradigm. But the idea is that you can specify an arbitrary number of nested loops and then the nesting is done for you by the compiler (or the runtime). So it's a kind of templated nesting where you define the loop conditions for an arbitrary number of loops and the environment constructs the loops for you.
For example
NestedParamsArrayLoop(delegatedFunction, loopContoller1); results in iterated calls to delegatedFunction(values for loopValue1);
NestedParamsArrayLoop(delegatedFunction, loopContoller1, loopController2); results in
iterated calls to delegatedFunction(values for loopValue1, values for loopValue2);
NestedParamsArrayLoop(delegatedFunction, values for loopContoller1, values for values for loopController2, loopController3); results in
iterated calls to delegatedFunction(loopValue1, values for loopValue2, values for loopValue3);
The goal of this is to avoid writing separate functions with different numbers of arguments but where the actual guts of the logic is common across them.
I hope I've done a decent job of explaining this but if not please ask!
I think this is pretty much what you want to do.
Start with a LoopController definition:
public class LoopController : IEnumerable<int>
{
public int Start;
public int End;
public int Increment;
private IEnumerable<int> Enumerate()
{
var i = this.Start;
while (i <= this.End)
{
yield return i;
i += this.Increment;
}
}
public IEnumerator<int> GetEnumerator()
{
return this.Enumerate().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
Now you can define NestedParamArrayLoop like so:
public double NestedParamArrayLoop(Func<int[], double> delegatedFunction, List<LoopController> loopControllers)
{
double total = 0;
foreach (LoopController loopController in loopControllers)
{
total += delegatedFunction(loopController.ToArray());
}
return total;
}
Now the rest is easy:
void Main()
{
var loopControllers = new List<LoopController>()
{
new LoopController() { Start = 4, End = 10, Increment = 2 },
new LoopController() { Start = 17, End = 19, Increment = 1 },
};
Console.WriteLine(NestedParamArrayLoop(DelegatedFunction, loopControllers));
}
public double DelegatedFunction(params int[] arguments)
{
long product = 1;
for (int i = 0; i < arguments.Count(); i++)
product *= arguments[i];
return product;
}
You could even define NestedParamArrayLoop as this:
public double NestedParamArrayLoop(Func<int[], double> delegatedFunction, List<LoopController> loopControllers)
{
return
loopControllers
.Select(lc => delegatedFunction(lc.ToArray()))
.Sum();
}
Is this more like what you're after?
public double NestedParamArrayLoop(Func<int[], double> delegatedFunction, List<LoopController> loopControllers)
{
Func<IEnumerable<int>, IEnumerable<IEnumerable<int>>> getAllSubsets = null;
getAllSubsets = xs =>
(xs == null || !xs.Any())
? Enumerable.Empty<IEnumerable<int>>()
: xs.Skip(1).Any()
? getAllSubsets(xs.Skip(1))
.SelectMany(ys => new[] { ys, xs.Take(1).Concat(ys) })
: new[] { Enumerable.Empty<int>(), xs.Take(1) };
double total = 0;
foreach (LoopController loopController in loopControllers)
{
foreach (var subset in getAllSubsets(loopController))
{
total += delegatedFunction(subset.ToArray());
}
}
return total;
}
Since the OP asked for a solution in any .NET language, I wrote one in F# (translating #Enigmativity's answer). No NestedLoopController class required:
[[ 4 .. 2 .. 10 ]; [ 17 .. 1 .. 19 ]]
|> Seq.map (fun args ->
(1L, args)
||> Seq.fold (fun a x -> a * int64 x))
|> Seq.sum
|> printfn "%d"
You can probably translate this to C# LINQ in a relatively straightforward way…
I think what you really need is what is called cartesian product of multiple sets. Here is good article from Eric Lippert about doing that with arbitrary number of sets in C#. So create function like this (I won't explain it because I cannot do this better than Eric did in his article):
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(params IEnumerable<T>[] sources) {
IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
foreach (var source in sources) {
var tmp = source;
result = result.SelectMany(
seq => tmp,
(seq, item) => seq.Concat(new[] { item }));
}
return result;
}
Then use like this:
foreach (var n in CartesianProduct(Enumerable.Range(1, 4), Enumerable.Range(1, 4))) {
Console.WriteLine(String.Join(", ", n));
// in your case: delegatedFunction(n);
}
outputs
1, 1
1, 2
1, 3
1, 4
2, 1
2, 2
2, 3
2, 4
3, 1
3, 2
3, 3
3, 4
4, 1
4, 2
4, 3
4, 4
It's easy to replace Enumerable.Range with your LoopController, Enumerable.Range is used just as an example.
I have a double[] array, i want to use it as key (not literally, but in the way that the key is matched when all the doubles in the double array need to be matched)
What is the fastest way to use the double[] array as key to dictionary?
Is it using
Dictionary<string, string> (convert double[] to a string)
or
anything else like converting it
Given that all key arrays will have the same length, either consider using a Tuple<,,, ... ,>, or use a structural equality comparer on the arrays.
With tuple:
var yourDidt = new Dictionary<Tuple<double, double, double>, string>();
yourDict.Add(Tuple.Create(3.14, 2.718, double.NaN), "da value");
string read = yourDict[Tuple.Create(3.14, 2.718, double.NaN)];
With (strongly typed version of) StructuralEqualityComparer:
class DoubleArrayStructuralEqualityComparer : EqualityComparer<double[]>
{
public override bool Equals(double[] x, double[] y)
{
return System.Collections.StructuralComparisons.StructuralEqualityComparer
.Equals(x, y);
}
public override int GetHashCode(double[] obj)
{
return System.Collections.StructuralComparisons.StructuralEqualityComparer
.GetHashCode(obj);
}
}
...
var yourDict = new Dictionary<double[], string>(
new DoubleArrayStructuralEqualityComparer());
yourDict.Add(new[] { 3.14, 2.718, double.NaN, }, "da value");
string read = yourDict[new[] { 3.14, 2.718, double.NaN, }];
Also consider the suggestion by Sergey Berezovskiy to create a custom class or (immutable!) struct to hold your set of doubles. In that way you can name your type and its members in a natural way that makes it more clear what you do. And your class/struct can easily be extended later on, if needed.
Thus all arrays have same length and each item in array have specific meaning, then create class which holds all items as properties with descriptive names. E.g. instead of double array with two items you can have class Point with properties X and Y. Then override Equals and GetHashCode of this class and use it as key (see What is the best algorithm for an overriding GetHashCode):
Dictionary<Point, string>
Benefits - instead of having array, you have data structure which makes its purpose clear. Instead of referencing items by indexes, you have nice named property names, which also make their purpose clear. And also speed - calculating hash code is fast. Compare:
double[] a = new [] { 12.5, 42 };
// getting first coordinate a[0];
Point a = new Point { X = 12.5, Y = 42 };
// getting first coordinate a.X
[Do not consider this a separate answer; this is an extension of #JeppeStigNielsen's answer]
I'd just like to point out that you make Jeppe's approach generic as follows:
public class StructuralEqualityComparer<T>: IEqualityComparer<T>
{
public bool Equals(T x, T y)
{
return StructuralComparisons.StructuralEqualityComparer.Equals(x, y);
}
public int GetHashCode(T obj)
{
return StructuralComparisons.StructuralEqualityComparer.GetHashCode(obj);
}
public static StructuralEqualityComparer<T> Default
{
get
{
StructuralEqualityComparer<T> comparer = _defaultComparer;
if (comparer == null)
{
comparer = new StructuralEqualityComparer<T>();
_defaultComparer = comparer;
}
return comparer;
}
}
private static StructuralEqualityComparer<T> _defaultComparer;
}
(From an original answer here: https://stackoverflow.com/a/5601068/106159)
Then you would declare the dictionary like this:
var yourDict = new Dictionary<double[], string>(new StructuralEqualityComparer<double[]>());
Note: It might be better to initialise _defaultComparer using Lazy<T>.
[EDIT]
It's possible that this might be faster; worth a try:
class DoubleArrayComparer: IEqualityComparer<double[]>
{
public bool Equals(double[] x, double[] y)
{
if (x == y)
return true;
if (x == null || y == null)
return false;
if (x.Length != y.Length)
return false;
for (int i = 0; i < x.Length; ++i)
if (x[i] != y[i])
return false;
return true;
}
public int GetHashCode(double[] data)
{
if (data == null)
return 0;
int result = 17;
foreach (var value in data)
result += result*23 + value.GetHashCode();
return result;
}
}
...
var yourDict = new Dictionary<double[], string>(new DoubleArrayComparer());
Ok this is what I found so far:
I input an entry (length 4 arrray) to the dictionary, and access it for 999999 times on my machine:
Dictionary<double[], string>(
new DoubleArrayStructuralEqualityComparer()); takes 1.75 seconds
Dictionary<Tuple<double...>,string> takes 0.85 seconds
The code below takes 0.1755285 seconds, which is the fastest now! (in line with the comment with Sergey.)
The fastest - The code of DoubleArrayComparer by Matthew Watson takes 0.15 seconds!
public class DoubleArray
{
private double[] d = null;
public DoubleArray(double[] d)
{
this.d = d;
}
public override bool Equals(object obj)
{
if (!(obj is DoubleArray)) return false;
DoubleArray dobj = (DoubleArray)obj;
if (dobj.d.Length != d.Length) return false;
for (int i = 0; i < d.Length; i++)
{
if (dobj.d[i] != d[i]) return false;
}
return true;
}
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
for (int i = 0; i < d.Length;i++ )
{
hash = hash*23 + d[i].GetHashCode();
}
return hash;
}
}
}
I have a huge list of checks that checks for example if integer is 4 or 10, if it is 4 it changes this int to 10 and Vice versa so my if check would be something like this:
int i = getval();
if (i == 4)
{
i = 10;
}
else if (i == 10)
{
i = 4;
}
My question is there another way to do this without the need to check for each condition.
If you have a huge list you might consider some list structure.
static Dictionary<int, int> exchange = new Dictionary<int, int>();
static Constructor()
{
AddExchangePair(4, 10);
AddExchangePair(3, 12);
...
}
static void AddExchangePair(int a, int b)
{
exchange.Add(a,b);
exchange.Add(b,a);
}
public staic bool Exchange(ref int value)
{
int newValue = 0;
bool exchanged = exchange.TryGetValue(value, out newValue);
if (exchanged) value = newValue;
return exchanged;
}
This works for huge lists of exchange pairs.
If you call AddExchangePair with a duplicate number e.g. (7,14) and (14, 16) you will get an exception. You might have to consider what to do in that case.
You are looking for the switch statement.
int i = getval();
switch(i)
{
case 4:
i = 10;
break;
case 10:
i = 4;
break;
default:
Console.WriteLine("Invalid selection. Please select 4 or 10.");
break;
}
I disagree with using a switch given that you have a "huge list of checks". I would make the checks its own class backed by a Dictionary. This will help minimize the size of your switch statement, and enforce a separation of the checks and the rest of your code:
class Cases
{
private static readonly Dictionary<int, int>
List = new Dictionary<int, int>
{
{9, 5},
{3, 2},
{7, 12},
{4, 10}
};
public static int GetCaseValue (int v)
{
int result = 0;
return List.TryGetValue(v, out result) ? result : v;
}
}
class Program
{
public static void Main()
{
var test = Cases.GetCaseValue(4);
test = Cases.GetCaseValue(12);
}
}
switch(i)
{
case 4 : i=10; break;
case 10: i=4; break;
}
You won't get around some sort of if / switch statement, since there is no easy way to go from 4 to 10 and back.
If it is 0 and X you swap between, you can go variable = X - variable; which swaps it just fine, but for 4 and 10 the above code is fine.
Try this:
int i = getval() == 4 ? 10 : 4;
That should check if getval() is 4 and then toggle between 4 and 10.
This is what you want.
int i = getval();
switch (i)
{
case 4:
i=10;
break;
case 10:
i=4;
break;
}
Someone beat me to this (and wrote it arguable better) but since I wrote the code I'm posting it anyway.
I'll also throw in that the use of ref here is probably in both our answers only to maintain compliance with your question and in reality something like this would probably use a functional approach so instead of calling Swap(ref i) it would call i = Swap(i) and Swap would return it's input if it found no match. Of course there might be a reason you need to use ref - I just can't think of an obvious one off the top of my head.
void Main()
{
int i;
i = 1;
Swap(ref i); // no swap
Console.WriteLine (i);
i = 10;
Swap(ref i); // swap with 4
Console.WriteLine (i);
i = 4;
Swap(ref i); // swap with 10
Console.WriteLine (i);
}
void Swap(ref int i)
{
if(swaps == null)
{
swaps = new List<Tuple<int, int>>();
swaps.Add(Tuple.Create(4, 10));
}
int compareTo = i;
var swap1 = from c in swaps where c.Item1 == compareTo select c.Item2;
var swap2 = from c in swaps where c.Item2 == compareTo select c.Item1;
if(swap1.Any())
i = swap1.Single();
else if(swap2.Any())
i = swap2.Single();
}
List<Tuple<int, int>> swaps;
Output:
1
4
10