i have this:
private static List<Mod> m_modList;
public static void UpdateScript(Script rScript)
{
for (int i = 0; i < m_modList.Count; i++)
for (int b = 0; b < m_modList[i].scriptModule.Count; b++)
for (int m = 0; m < m_modList[i].scriptModule[b].scripts.Count; m++)
if (m_modList[i].scriptModule[b].scripts[m].name == rScript.name)
m_modList[i].scriptModule[b].scripts[m] = rScript;
}
can I somehow reduce the amount of code, and not use so many for loops?
First, you could simplify your code for better understanding (even for yourself) :
foreach(Mod mod in m_modList)
{
foreach(ScriptMod scriptMod in mod.scriptModule)
{
for(int i = 0;i<scriptMod.scripts.Count();i++)
{
if(scriptModule.scripts[i].name==rScript.name)
scriptModule.scripts[i]=rScript;
}
}
}
You eventually could simplify it like that :
foreach(ScriptModule scriptMod in m_modList.SelectMany(x=>x.scriptModule))
{
for(int i = 0;i<scriptModule.scripts.Count();i++)
{
if(scriptModule.scripts[i].name==rScript.name)
scriptModule.scripts[i]=rScript;
}
}
in the case scriptModule.scripts[i]=rScript; could be replaced by a Clone, you can use several SelectMany :
foreach(Script script in m_modList.SelectMany(x=>x.scriptModule.SelectMany(y=>y.scripts)))
{
if(script.Name==rScript.Name)
{
script.Clone(rScript);
}
}
(cannot assign an object in foreach).
Related
I am wondering why if I change the line
"sub = sub.SelectMany(x => x.Next(i)).ToList();"
to
"sub = sub.SelectMany(x => x.Next(i));"
I get the error
Line 48: System.IndexOutOfRangeException: Index was outside the bounds of the array" when I provide an input of 4 to the method SolveNQueens.
I believe it may have something to do with lazy evaluation.
The full code sample is listed below and is a valid solution
to the n queens problem.
public class Solution {
public IList<IList<string>> SolveNQueens(int n)
{
IEnumerable<PartialQueens> sub = new List<PartialQueens>(){
new PartialQueens(n)};
for(int i=0;i<n;i++)
{
sub = sub.SelectMany(x => x.Next(i)).ToList();
}
return sub.Select(x => x.ToPosition()).ToList();
}
}
public class PartialQueens
{
public byte FREE = 0;
public byte BLOCKED = 1;
public byte QUEEN = 2;
public byte[,] fill;
int n;
public PartialQueens(int n)
{
this.n = n;
fill = new byte[n,n];
}
public PartialQueens(byte[,] fill, int n)
{
this.fill = fill;
this.n = n;
}
public PartialQueens Fill(int row, int column)
{
byte[,] newFill = fill.Clone() as byte[,];
newFill[row,column] = QUEEN;
Action<int,int> f = (x,y) =>
{
if(y >= 0 && y < n)
newFill[x,y] = BLOCKED;
};
for(int i=1;i<n-row;i++)
{
f(row+i,column+i);
f(row+i,column-i);
f(row+i,column);
}
return new PartialQueens(newFill,n);
}
public IEnumerable<PartialQueens> Next(int row)
{
for(int j=0;j<n;j++)
{
if(fill[row,j] == FREE)
yield return Fill(row,j);
}
}
public IList<string> ToPosition()
{
return Enumerable.Range(0,n).Select(i => ConvertRow(i)).ToList();
}
public string ConvertRow(int i)
{
StringBuilder builder = new StringBuilder();
for(int j=0;j<n;j++)
{
if(fill[i,j] == QUEEN)
builder.Append("Q");
else
builder.Append(".");
}
return builder.ToString();
}
}
The reason this fails is because of the way that the iterator variable used in a for loop is evaluated when it is captured by a closure. When you remove the ToList() inside the loop, the sub IEnumerable is only evaluated when sub is materialized in the return statement return sub.Select(x => x.ToPosition()).ToList();. At this time, the for loop variable i will have a value of n (e.g. 8 on a standard chess board), which is outside the array bounds.
However, when you materialize the List immediately, the side effect isn't encountered, since the value of i is used before the next iteration (ToList materializes).
Works:
for (int i = 0; i < n; i++)
{
// Materialized here so `i` evaluated immediately
sub = sub.SelectMany(x => x.Next(i)).ToList();
}
Broken:
for (int i = 0; i < n; i++)
{
sub = sub.SelectMany(x => x.Next(i));
}
return sub.Select(x => x.ToPosition()).ToList(); // `i` evaluated here
To fix the for loop variable evaluation issue, you can explicitly capture the current value of the iterator variable:
for (int i = 0; i < n; i++)
{
var loop = i;
sub = sub.SelectMany(x => x.Next(loop)); // No To List - lazy evaluation
}
Re : Avoiding for loops in FP Paradigm code
OP's SolveNQueens method uses a loop which progressively changes the sub, rather than recursion, but the for can also be replaced with a foreach and a range:
foreach(var i in Enumerable.Range(0, n))
{
sub = sub.SelectMany(x => x.Next(i));
}
Which Resharper then offers to re-write as a left fold:
sub = Enumerable.Range(0, n)
.Aggregate(sub, (current, i) => current.SelectMany(x => x.Next(i)));
Either way, the flaw in lazy evaluation of the iterator variable inside a for loop is avoided.
im frenchi so sorry first sorry for my english .
I have an error on visual studio (index out of range) i have this problem only with a Parallel.For not with classic for.
I think one thread want acces on my array[i] and another thread want too ..
It's a code for calcul Kmeans clustering for building link between document (with cosine similarity).
more information :
IndexOutOfRange is on similarityMeasure[i]=.....
I have a computer with 2 Processor (12logical)
with classic for , cpu usage is 9-14% , time for 1 iteration=9min..
with parallel.for , cpu usage is 70-90% =p, time for 1 iteration =~1min30
Sometimes it works longer before generating an error
My function is :
private static int FindClosestClusterCenter(List<Centroid> clustercenter, DocumentVector obj)
{
float[] similarityMeasure = new float[clustercenter.Count()];
float[] copy = similarityMeasure;
object sync = new Object();
Parallel.For(0, clustercenter.Count(), (i) => //for(int i = 0; i < clustercenter.Count(); i++) Parallel.For(0, clustercenter.Count(), (i) => //
{
similarityMeasure[i] = SimilarityMatrics.FindCosineSimilarity(clustercenter[i].GroupedDocument[0].VectorSpace, obj.VectorSpace);
});
int index = 0;
float maxValue = similarityMeasure[0];
for (int i = 0; i < similarityMeasure.Count(); i++)
{
if (similarityMeasure[i] > maxValue)
{
maxValue = similarityMeasure[i];
index = i;
}
}
return index;
}
My function is call here :
do
{
prevClusterCenter = centroidCollection;
DateTime starttime = DateTime.Now;
foreach (DocumentVector obj in documentCollection)//Parallel.ForEach(documentCollection, parallelOptions, obj =>//foreach (DocumentVector obj in documentCollection)
{
int ind = FindClosestClusterCenter(centroidCollection, obj);
resultSet[ind].GroupedDocument.Add(obj);
}
TimeSpan tempsecoule = DateTime.Now.Subtract(starttime);
Console.WriteLine(tempsecoule);
//Console.ReadKey();
InitializeClusterCentroid(out centroidCollection, centroidCollection.Count());
centroidCollection = CalculMeanPoints(resultSet);
stoppingCriteria = CheckStoppingCriteria(prevClusterCenter, centroidCollection);
if (!stoppingCriteria)
{
//initialisation du resultat pour la prochaine itération
InitializeClusterCentroid(out resultSet, centroidCollection.Count);
}
} while (stoppingCriteria == false);
_counter = counter;
return resultSet;
FindCosSimilarity :
public static float FindCosineSimilarity(float[] vecA, float[] vecB)
{
var dotProduct = DotProduct(vecA, vecB);
var magnitudeOfA = Magnitude(vecA);
var magnitudeOfB = Magnitude(vecB);
float result = dotProduct / (float)Math.Pow((magnitudeOfA * magnitudeOfB),2);
//when 0 is divided by 0 it shows result NaN so return 0 in such case.
if (float.IsNaN(result))
return 0;
else
return (float)result;
}
CalculMeansPoint :
private static List<Centroid> CalculMeanPoints(List<Centroid> _clust)
{
for (int i = 0; i < _clust.Count(); i++)
{
if (_clust[i].GroupedDocument.Count() > 0)
{
for (int j = 0; j < _clust[i].GroupedDocument[0].VectorSpace.Count(); j++)
{
float total = 0;
foreach (DocumentVector vspace in _clust[i].GroupedDocument)
{
total += vspace.VectorSpace[j];
}
_clust[i].GroupedDocument[0].VectorSpace[j] = total / _clust[i].GroupedDocument.Count();
}
}
}
return _clust;
}
You may have some side effects in FindCosineSimilarity, make sure it does not modify any field or input parameter. Example: resultSet[ind].GroupedDocument.Add(obj);. If resultSet is not a reference to locally instantiated array, then that is a side effect.
That may fix it. But FYI you could use AsParallel for this rather than Parallel.For:
similarityMeasure = clustercenter
.AsParallel().AsOrdered()
.Select(c=> SimilarityMatrics.FindCosineSimilarity(c.GroupedDocument[0].VectorSpace, obj.VectorSpace))
.ToArray();
You realize that if you synchronize the whole Content of the Parallel-For, it's just the same as having a normal synchrone for-loop, right? Meaning the code as it is doesnt do anything in parallel, so I dont think you'll have any Problems with concurrency. My guess from what I can tell is clustercenter[i].GroupedDocument is propably an empty Array.
I'm trying to sort a list of strings in alphabetical order in C#. My code looks like this:
public static List<Result> sort(List<Result> listToSort)
{
int listSize = listToSort.Count;
for (int i = 0; i < listSize; i++)
{
for (int j = 0; j < listSize; j++)
{
if (listToSort[i].SN[0] < listToSort[j].SN[0])
{
Result tempValue = listToSort[j];
listToSort[j] = listToSort[i];
listToSort[i] = tempValue;
}
}
}
return listToSort;
}
But it's only sorting it based on the first letter of a string. In other words, if I have a list like this:
donald, abby, dave, bob, sam, pete
It will sort it like so:
abby, bob, donald, dave, pete, sam
One would expect 'dave' to come before 'donald'..
Any ideas?
Currently you are only sorting by the first letter that is why you are seeing this result. You can use Enumerable.OrderBy - LINQ
List<Result> sortedList = listToSort.OrderBy(r=> r.SN).ToList();
Or for your current code you can modify your check to:
if (string.Compare(listToSort[i].SN,listToSort[j].SN) < 0)
How about using LINQ for this:
return listToSort.OrderBy(report => report.SN)
I'm assuming your Report class has a string property you want the list to be sorted by?
EDIT
Didn't notice that you'd already specified the SN property, have amended my answer.
public static List<Result> sort(List<Result> listToSort)
{
return listToSort.OrderBy(x=>x.SN[0]).ToList();
}
You're only ever evaluating the first letter. Try using the traditional sorting method:
public static void Sort(List<Result> listToSort)
{
listToSort.Sort(new ResultComparator());
}
public class ResultComparator : IComparer<Result>
{
public int Compare(Result x, Result y)
{
if (x == null && y == null) return 0;
if (x == null) return 1;
if (y == null) return 0;
// compare based in SN
return string.Compare(x.SN, y.SN);
}
}
Take a look at this part:
for (int i = 0; i < listSize; i++)
{
for (int j = 0; j < listSize; j++)
{
if (listToSort[i].SN[0] < listToSort[j].SN[0])
{
You are
only comparing on SN[0]. If SN is a string then that explains your main result.
always using the same compare, whether i < j or i > j
Best thing to do is to use a built-in sort. Linq's OrderBy(lambda) is the easiest but it creates a new list. For an in-place sort, use List<T>.Sort(Comparer).
If you do have to do it yourself, look up a good sorting algorithm (wikipedia).
It was happened because of comparing character of the first string (listToSort[i].SN[0] => which produces the first character of your input). If you want to compare the string values, you should use string.Compare() method.
--SJ
Something like:
forelement (element G_Element, Grid)
{
Grid[G_Element.dim1, G_Element.dim2] =
new clsGridElement(G_Element.dim1, G_Element.dim2);
}
instead of
for (int X = 0; X < GridWidth; X++)
for (int Y = 0; Y < GridHeight; Y++)
Grid[X, Y] = new clsGridElement(X, Y);
If something doesn't innately exist, is that something that could be created?
Thanks,
Tim
You could do this - just make a custom type that exposes these, and use a regular foreach:
public class TwoDimensionalIterator
{
public TwoDimensionalIterator(int i, int j)
{
this.Dim1 = i; this.Dim2 = j;
}
public int Dim1 { get; private set; }
public int Dim2 { get; private set; }
}
Then make an extension method somewhere to return an enumerable of this:
public static IEnumerable<TwoDimensionalIterator> IterateTwoDim<T>(this T[,] array)
{
for (int i=0;i<array.GetLength(0);++i)
for (int j=0;i<array.GetLength(1);++j)
yield return new TwoDimensionalIterator(i,j);
}
With this, you could then do:
foreach(var index in Grid.IterateTwoDim())
{
Grid[index.Dim1, index.Dim2] = new clsGridElement(index.Dim1, index.Dim2);
}
Not sure exactly what you are trying to do here, or why, or what you expect to get from it, but if you implement your own iterator than implements the IEnumerator interface then you could create something that would hit every cell in your 2D (or more) collection.
Of course, you won't actually gain anything performance-wise from doing this versus just using nested loops, but I guess it'd be syntactic sugar.
Such creation of indexes can be obtained by using "Cartesian product" of all indexes. Here is sample based on Is there a good LINQ way to do a cartesian product? (courtesy of the Eric Lippert):
var allIndexes = from dim1 in Enumerable.Range(0, Grid.GetLength(0))
from dim2 in Enumerable.Range(0, Grid.GetLength(1))
select new {dim1, dim2};
foreach (var G_Element in allIndexes)
{
Grid[G_Element.dim1, G_Element.dim2] =
new clsGridElement(G_Element.dim1, G_Element.dim2);
}
I am a rookie to C# and here is my question
class myClass
{
int start;
int end;
.......
}
class program
{
public void main()
{
myClass[] a= new myClass[10];
for (int i = 1; i < a.length; i++)
{
myClass b = new myClass();
a[i] = b;
a[i].start = 1;
... (keep populating)
...
}
console.writeline(a[1].start) // NO PROBLEM WITH THIS LINE, THE VALUE WAS OUTPUTED
subMethod(a);
}
public void subMethod(myClass[] a)
{
console.write(a[1].start); // NO PROBLEM WITH THIS LINE, OUTPUT NORMALLY
for (int i = 1; i < a.length, i++)
{
int h = a[i].start; ????? OBJECT NOT INSTANTIATED
}
}
}
The error is as indicated above and I have difficulty to understand it. Anyone can help me out. Thanks in advance
The problem seems to be in the code that you haven't posted.
myClass[] a= new myClass[10];
// (populate this array)
I've no idea what you have written there but it clearly isn't working. It should be this:
myClass[] a = new myClass[10];
for (int i = 0; i < a.Length; i++)
{
a[i] = new myClass();
}
The code you posted won't compile. Please copy + paste the actual code - don't try to write it from memory.
You should notice that the first index in an array is 0, not 1.
I'd also suggest that you read the Microsoft naming guidelines, for example class names should be in Pascal case.
You've instantiated an array but new need to instantiate each object in the array. You are not showing how you do that bit in the example above.
Please post code that compiles. The error is probably in your transcribing of the code, because this code works perfectly fine:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RandomArrayTest
{
class MyClass
{
public int start;
}
class Program
{
static void Main(string[] args)
{
MyClass[] a = new MyClass[10];
for(int i=1; i<a.Length; i++)
{
MyClass b = new MyClass();
a[i] = b;
a[i].start = 1;
}
MyFunction(a);
}
static void MyFunction(MyClass[] a)
{
for (int i = 1; i < a.Length; i++)
{
int h = a[i].start;
Console.WriteLine(h);
}
}
}
}