I would like to create a list where I have 10 main points and associated 4 minor points as a List to each main point.
Lets say I have a class definition like this and a method:
public class Abc{
public Point2D MainPoint { get; set; }
public List<Point2D> MinorPoints { get; set; }
public static List<Abc> AddValues(){
var result = new List<Abc>();
List<Point2D> newMinorPointsList = new List<Point2D>();
for (int i = 0; i < 10; i++){
var newMainPoint = new Point2D(10 * i, 5 * i);
for (int j = 0; j < 4; j++){
var newMinorPoint = new Point2D(20 * i * j, 10 * i * j);
newMinorPointsList.Add(newMinorPoint);
}
result.Add( new Abc() { MainPoint = newMainPoint, MinorPoints = new List<Point2D>(newMinorPointsList)});
}
}
public static string PrintValues(List<Abc> pointList){
string result = "";
string resultMain = "";
string resultMinor = "";
string resultMinorString = "";
var allPoints = new Abc();
for (int i = 0; i < pointList.Count; i++){
allPoints.MainPoint = pointList[i].MainPoint;
allPoints.MinorPoints = new List<Point2D>(pointList[i].MinorPoints);
for (int j = 0; j < allPoints.MinorPoints.Count; j++){
resultMinor = allPoints.MinorPoints[j] + ", ";
resultMinorString += resultMinor;
}
resultMain = "Main Point: " + allPoints.MainPoint + ", Minor Points: " + resultMinorString;
result += resultMain;
}
}
But I'm getting null reference exception at allPoints.MinorPoints = new List(pointList[i].MinorPoints); and it looks like values are not added into MinorPoints. What am I doing wrong?
Here is a re-write of your code:
public static List<Abc> CreateListOfAbc() {
var result = new List<Abc>();
for (int i = 0; i < 10; i++)
result.Add(new Abc() {
MainPoint = new Point2D(10 * i, 5 * i),
MinorPoints = Enumerable.Range(0, 4).Select(j => new Point2D(20 * i * j, 10 * i * j)).ToList()
});
return result;
}
public static string PrintListOfAbc(List<Abc> pointList) {
string result = "";
foreach (var p in pointList)
result += $"Main Point: {p.MainPoint}, Minor Points: {String.Join(", ", p.MinorPoints)}\n";
return result;
}
Related
So I'm trying to sort a list of books that have been added to an array alphabetically however, whenever I input the third book, the list flips and sorts the list in unalphabetical order.
If anyone knows why this is, please comment and let me know, my code is below.
The sort to determine if two indexes need to be swapped
private void bookSort()
{
for (int y = 0; y < 20; y++)
{
for (int x = 0; x < bookPTR - 1; x++)
{
if (string.Compare(books[x].GStitle, books[x + 1].GStitle) > 0)
{
bookSwapRoutine(books[x]);
}
}
}
}
The swap itself
private void bookSwapRoutine(Book book, int x = 0)
{
string tempString = books[x].GStitle;
books[x].GStitle = books[x + 1].GStitle;
books[x + 1].GStitle = tempString;
int tempInt = books[x].GSisbn;
books[x].GSisbn = books[x + 1].GSisbn;
books[x + 1].GSisbn = tempInt;
tempString = books[x].GSauthor;
books[x].GSauthor = books[x + 1].GSauthor;
books[x + 1].GSauthor = tempString;
tempString = books[x].GSpublisher;
books[x].GSpublisher = books[x + 1].GSpublisher;
books[x + 1].GSpublisher = tempString;
double tempDouble = books[x].GSprice;
books[x].GSprice = books[x + 1].GSprice;
books[x + 1].GSprice = tempDouble;
tempString = books[x].GSdate;
books[x].GSdate = books[x + 1].GSdate;
books[x + 1].GSdate = tempString;
}
Because of this place. That function call always swap books at zero index and first index because of default parameter x = 0.
bookSwapRoutine(books[x]);
You should call it like.
bookSwapRoutine(books[x], x);
This will swap books[x] and books[x + 1] for you.
If you want just sort your books by GStitle in alphabeticall order you can call.
Array.Sort(books, (x, y) => string.Compare(x.GStitle, y.GStitle, StringComparison.InvariantCulture));
Here all code, with correct bubble sort, if it will help you.
public static void Main()
{
var books = new Book[]
{
new Book() {GStitle = "E"},
new Book() {GStitle = "D"},
new Book() {GStitle = "C"},
new Book() {GStitle = "B"},
new Book() {GStitle = "A"}
};
Console.WriteLine("Before sort.");
foreach (var book in books)
{
Console.WriteLine(book.GStitle);
}
Array.Sort(books, (x, y) => string.Compare(x.GStitle, y.GStitle, StringComparison.InvariantCulture));
//BookSort(books);
Console.WriteLine("After sort.");
foreach (var book in books)
{
Console.WriteLine(book.GStitle);
}
}
public class Book
{
public string GStitle { get; set; }
}
public static void BookSort(Book[] books)
{
for (int y = 0; y < books.Length; y++)
{
for (int x = 0; x < books.Length - 1 - y; x++)
{
if (string.Compare(books[x].GStitle, books[x + 1].GStitle, StringComparison.InvariantCulture) > 0)
{
var temp = books[x];
books[x] = books[x + 1];
books[x + 1] = temp;
}
}
}
}
Trying to build Array of Lists of Structs in C#. And getting a System.NullReferenceException with the best try (error on line test[i].Add(info1);)
The question is not how to avoid System.NullReferenceException at all, but more like how to quickly build Array of Lists with predefined size of array, thus that one is able to use array[i].Add(Struct) in it. If possible without looping all over the array, just to create the lists.
So these are the requirements:
the size of the array should be predefined;
the numbers of the lists per node should be arbitrary, and there should be a possibility that these are added easily;
the structure should contain the struct Info.
This is the code, I have managed so far (copy and paste should work, to replicate the error):
using System.Collections.Generic;
class Startup
{
static void Main()
{
int entry = 1233;
List<Info>[] test = new List<Info>[entry];
for (int i = 0; i < 500 ; i+=3)
{
Info info1 = new Info()
{
capacity = i * 2,
name = i.ToString()
};
test[i].Add(info1);
}
for (int i = 0; i < 1000; i+=5)
{
Info info2 = new Info();
info2.capacity = i * 2;
info2.name = i.ToString() + i.ToString();
test[i].Add(info2);
}
}
struct Info
{
public int capacity;
public string name;
}
}
Each element of a the array are not defined as the object is a List
This is how you should do it :
using System.Collections.Generic;
class Startup
{
static void Main()
{
int entry = 1233;
List<Info>[] test = new List<Info>[entry];
for (int i = 0; i < 500 ; i+=3)
{
Info info1 = new Info()
{
capacity = i * 2,
name = i.ToString()
};
// if null initialise the list
if(test[i] == null) test[i] = new List<Info>();
test[i].Add(info1);
}
for (int i = 0; i < 1000; i+=5)
{
Info info2 = new Info();
info2.capacity = i * 2;
info2.name = i.ToString() + i.ToString();
// if null initialise the list
if(test[i] == null) test[i] = new List<Info>();
test[i].Add(info2);
}
}
struct Info
{
public int capacity;
public string name;
}
}
Try this:
using System.Collections.Generic;
class Startup
{
static void Main()
{
int entry = 1233;
List<Info>[] test = new List<Info>[entry];
for (int i = 0; i < 500 ; i+=3)
{
Info info1 = new Info()
{
capacity = i * 2,
name = i.ToString()
};
test[i] = new List<Info> {info1};
}
for (int i = 0; i < 1000; i += 5)
{
Info info2 = new Info();
info2.capacity = i * 2;
info2.name = i.ToString() + i.ToString();
if (test[i] == null)
{
test[i] = new List<Info> { info2 };
}
else
{
test[i].Add(info2);
}
}
}
struct Info
{
public int capacity;
public string name;
}
}
Try this:
using System.Collections.Generic;
class Startup
{
static void Main()
{
int entry = 1233;
var test = Enumerable.Range(0,entry)
.Select(i=> {
var y = new List<Info>();
if(i%3==0 && i < 500)
{
y.Add(new Info {
capacity = i*2,
name = i.ToString()
});
}
if(i%5==0 && i < 1000)
{
y.Add(new Info {
capacity = i*2,
name = i.ToString() + i.ToString()
});
}
return y;
}).ToArray();
}
struct Info
{
public int capacity;
public string name;
}
}
I am having issues in calculation of cosine similarity between 2 strings.
I calculate the binary vector format of each string using a function. It gives out binary vectors which are in the form of, say, (1,1,1,1,1,0,0,0,0).
public static Tuple<int[],int[]> sentence_to_vector(String[] word_array1, String[] word_array2)
{
String[] unique_word_array1 = word_array1.Distinct().ToArray();
String[] unique_word_array2 = word_array2.Distinct().ToArray();
String[] list_all_words = unique_word_array1.Concat(unique_word_array2).ToArray();
String[] list_all_words_unique = list_all_words.Distinct().ToArray();
int count_all_unique_words = list_all_words_unique.Length;
int[] sentence1_vector = new int[count_all_unique_words];
int[] sentence2_vector = new int[count_all_unique_words];
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(unique_word_array1, list_all_words_unique[i]) >= 0)
{
sentence1_vector[i] = 1;
}
else
{
sentence1_vector[i] = 0;
}
}
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(word_array2, list_all_words_unique[i]) >= 0)
{
sentence2_vector[i] = 1;
}
else
{
sentence2_vector[i] = 0;
}
}
return Tuple.Create(sentence1_vector, sentence2_vector);;
}
After I calculate the vector representation, I go for cosine similarity calculation.
The code is attached herewith:
public static float get_cosine_similarity(int[] sentence1_vector, int[] sentence2_vector)
{
int vector_length = sentence1_vector.Length;
int i = 0;
float numerator = 0, denominator = 0;
int temp1 = 0, temp2 = 0;
double square_root1 = 0, square_root2 = 0;
for (i = 0; i < vector_length; i++)
{
numerator += sentence1_vector[i] * sentence2_vector[i];
temp1 += sentence1_vector[i] * sentence1_vector[i];
temp2 += sentence2_vector[i] * sentence2_vector[i];
}
//TextWriter tw = new StreamWriter("E://testpdf/date2.txt");
square_root1 = Math.Sqrt(temp1);
square_root2 = Math.Sqrt(temp2);
denominator = (float)(square_root1 * square_root2);
if (denominator != 0){
return (float)(numerator / denominator);
//return (float)(numerator);
}
else{
return 0;
}
}
I checked out a site where in I can specify 2 strings and find the cosine similarity between them. The site is attached herewith:
http://cs.uef.fi/~zhao/Link/Similarity_strings.html
function implementationCosin(){
var string1 = document.DPAform.str1.value;
var s1 = stringBlankCheck(string1);
var string2 = document.DPAform.str2.value;
var s2 = stringBlankCheck(string2);
if (s1.length < 1) {
alert("Please input the string1.");
return;
}
if (s2.length < 1) {
alert("Please input the string2.");
return;
}
document.DPAform.displayArea2.value = "";
var sDT = new Date();
// var begin = new Date().getTime();
var cosin_similarity_value = consinSimilarity(s1, s2);
document.DPAform.displayArea2.value += 'Cosin_Similarity(' + s1 + ',' + s2 + ')=' + cosin_similarity_value + '%\n';
var eDT = new Date();
var timediff = sDT.dateDiff("ms", eDT);
// var timediff = (new Date().getTime() - begin);
document.DPAform.displayArea2.value += "The total escaped time is: " + timediff + " (ms).\n";
}
Even if 2 sentences are 0% similar, my codes says that there is some amount of similarity between them.
I have written 3 classes: KompresorSilnik, KompresorObiekt and Mrowka.
I want to create a matrix of objects of class KompresorObiekt ( it's a GrafObiektow method ). In the constructor of KompresorObiekt, I create 4 instances of KompresorSilnik. I have a method, zwrocListe() which returns a list of int[] from 0000 to 2222.
The question is: was that correct or not implementation?
public class KompresorSilnik
{
public double minFlow;
public double maxFlow;
public bool typ;
public int stan;
public KompresorSilnik()
{
}
public KompresorSilnik(double minFlow, double maxFlow, bool typ, int stan)
{
this.minFlow = minFlow;
this.maxFlow = maxFlow;
this.typ = typ;
this.stan = stan;
}
}
This is my second class KompresorObiekt
public class KompresorObiekt
{
public KompresorObiekt() { }
public KompresorObiekt( List<int[]> list, int x, int y)
{
double k1Max = 3000000.0;
double k1Min = 10000.0;
double k2Max = 200000.0;
double k2Min = 5000.0;
double K3Max = 100000000.0;
double k3Min = 800.0;
double k4Max = 10000.0;
double k4Min = 2000.0;
KompresorSilnik komp1 = new KompresorSilnik(k1Min, k1Max, false, list[x][y]);
KompresorSilnik komp2 = new KompresorSilnik(k2Min, k2Max, true, list[x][y+1]);
KompresorSilnik komp3 = new KompresorSilnik(k3Min, K3Max, false, list[x][y+2]);
KompresorSilnik komp4 = new KompresorSilnik(k4Min, k4Max, true, list[x][y+3]);
}
}
and the last one Mrowka
public class Mrowka
{
List<int[]> zwrocListe()
{
List<int[]> arrList = new List<int[]>();
int[] ArrayOfInts = new int[4];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
for (int m = 0; m < 3; m++)
{
ArrayOfInts[0] = i;
ArrayOfInts[1] = j;
ArrayOfInts[2] = k;
ArrayOfInts[3] = m;
int[] arc = (int[])ArrayOfInts.Clone();
arrList.Add(arc);
}
}
}
}
return arrList;
}
KompresorObiekt[][] GrafObiektow(int time)
{
KompresorObiekt[][] graf = new KompresorObiekt[time][];
int numNodes = zwrocListe().Count;
for (int i = 0; i < graf.Length; ++i)
graf[i] = new KompresorObiekt[numNodes];
for (int i = 0; i < time; ++i)
for (int j = 0; j < numNodes; ++j)
{
graf[i][j] = new KompresorObiekt(zwrocListe(), j, 0);
}
return graf;
}
}
Could anyone show me how to populate the Galaxy class with data dynamically?
public class Galaxy
{
public string Name {get; set;}
public string Distance {get:set;}
}
Instead of populating it manually:
var theGalaxies = new List<Galaxy>
{
new Galaxy() {Name="Tadpole", Distance="200"},
new Galaxy() {Name="Andromeda", Distance="300"}
};
I want to populate it dynamically. However, this code can't be compiled because of the for loop:
var theGalaxies = new List<Galaxy>
{
for (int i=0; i < someArray.Length; i++)
{
new Galaxy() {Name=someArray[0], distance=someArray[1]}
}
};
foreach (Galaxy theGalaxy in theGalaxies)
{
Console.WriteLine(theGalaxy.Name + " " + theGalaxy.Distance);
}
var theGalaxies = Enumerable.Range(0, 1000)
.Select(x => new Galaxy { Name = "Galaxy" + x.ToString(), Distance = x.ToString() })
.ToList();
You can't use loop in object initializer, instead try it like:
var theGalaxies = new List<Galaxy>();
for (int i=0; i < someArray.Length; i++)
theGalaxies.Add(new Galaxy() {Name=someArray[0], distance=someArray[1]});
Change your for loop code to this:
var theGalaxies = new List<Galaxy>();
for (int i=0; i < someArray.Length; i++)
{
var temp = new Galaxy();
temp.Name = someArray[0];
temp.Distance = someArray[1];
theGalaxies.Add(temp);
}
Assuming someArray alternates galaxy names and distances:
var theGalaxies = new List<Galaxy>();
for (int i=0; i < someArray.Length; i+=2)
theGalaxies.Add(new Galaxy() {Name=someArray[i], Distance=someArray[i+1]});
Parametered constructors are also nice:
public class Galaxy
{
public Galaxy(string name, string distance)
{
Name = name;
Distance = distance;
}
public string Name {get; set;}
public string Distance {get:set;}
}
//...
var theGalaxies = new List<Galaxy>();
for (int i=0; i < someArray.Length; i+=2)
theGalaxies.Add(new Galaxy(someArray[i], someArray[i+1]));
it looks like c#.
var theGalaxies = new List<Galaxy>():
Galaxy galxy;
for (int i = 0; i < someArray.Length; i++)
{
galxy =new Galaxy() {Name = someArray[0], distance = someArray[1]};
theGalaxies.Add(galxy);
};