Linq Total Based on Location - c#

I have the following code which does the job of returning a list of records totalling the stock at each location. I am trying to clean up the program before I take it any further. Is there a way to do the same thing with LINQ? I know this is a mess, and I would like to refine it.
Thanks for looking!
private static List < Stock_Paper_Record > Get_Final_List(List < Stock_Paper_Record > Finallist, List < Stock_Paper_Record > papr, List < string > Codes, List < string > locs) {
int ii = 0;
int totalg = 0;
int totall = 0;
int totalp = 0;
decimal gsm = 0;
decimal size1 = 0;
decimal size2 = 0;
int commited = 0;
int OnOrder = 0;
int THRESH = 0;
int iount = 0;
papr.Sort((x, y) => String.Compare(x.Code, y.Code));
Finallist.Sort((x, y) => String.Compare(x.Code, y.Code));
int ic = 0;
int it = 0;
List < string > ls = new List < string > ();
List < decimal > st = new List < decimal > ();
foreach(string s in Codes) {
for (int iii = 0; iii < papr.Count; iii++) {
if (s == papr[iii].Code && papr[iii].Location == "GLASGOW") {
totalg += Convert.ToInt32(papr[iii].Stock);
gsm = papr[iii].Grammage;
size1 = papr[iii].Size1;
size2 = papr[iii].Size2;
commited = papr[iii].Commited;
OnOrder = papr[iii].Onorderi;
THRESH = papr[iii].Threshholdi;
}
if (s == papr[iii].Code && papr[iii].Location == "LONDON") {
totall += Convert.ToInt32(papr[iii].Stock);
gsm = papr[iii].Grammage;
size1 = papr[iii].Size1;
size2 = papr[iii].Size2;
commited = papr[iii].Commited;
OnOrder = papr[iii].Onorderi;
THRESH = papr[iii].Threshholdi;
}
if (s == papr[iii].Code && papr[iii].Location == "PARIS") {
totalp += Convert.ToInt32(papr[iii].Stock);
gsm = papr[iii].Grammage;
size1 = papr[iii].Size1;
size2 = papr[iii].Size2;
commited = papr[iii].Commited;
OnOrder = papr[iii].Onorderi;
THRESH = papr[iii].Threshholdi;
} else {}
}
Finallist.Add(new Stock_Paper_Record() {
Location = "BOTH", Code = Codes[iount], Stocki = totalg + totall + totalp + OnOrder, BBstocki = totalg, Lmstocki = totall, Ingstocki = totalp, Commited = commited, Ballance = (totalg + totall + totalp + OnOrder) - commited, Size1 = size1, Size2 = size2, Grammage = gsm, Threshholdi = THRESH, Onorderi = OnOrder
});
totalg = 0;
totall = 0;
totalp = 0;
ii++;
iount++;
}
return Finallist;
}

This will be pretty close, however, if you supply a code that there is no records for, this will not return a record for it with all 0's, but your original code did. Not sure if that matters to you or not.
private static List<Stock_Paper_Record> Get_Final_List(List<Stock_Paper_Record> Finallist, List<Stock_Paper_Record> papr, List<string> Codes, List<string> locs) {
return papr
.Where(p=>Codes.Contains(p.Location))
.GroupBy(p=>p.Code)
.Select(g=>new {
Code=g.Key,
BBstocki=g.Where(p=>p.Location=="GLASGOW").Sum(p=>Convert.ToInt32(p.Stock)),
Lmstocki=g.Where(p=>p.Location=="LONDON").Sum(p=>Convert.ToInt32(p.Stock)),
Ingstocki=g.Where(p=>p.Location=="PARIS").Sum(p=>Convert.ToInt32(p.Stock)),
Commited=g.FirstOrDefault().Commited,
Size1=g.FirstOrDefault().Size1,
Size2=g.FirstOrDefault().Size2,
Grammage=g.FirstOrDefault().Grammage,
Threshholdi=g.FirstOrDefault().Threshholdi,
Onorderi=g.FirstOrDefault().Onorderi
}).Select(g=>new Stock_Paper_Record {
Location="BOTH",
Code=g.Code,
BBstocki=g.BBstocki,
Lmstocki=g.Lmstocki,
Ingstocki=g.Ingstocki,
Commited=g.Commited,
Size1=g.Size1,
Size2=g.Size2,
Grammage=g.Grammage,
Threshholdi=g.Threshholdi,
Onorderi=g.Onorderi,
Stocki=g.BBstocki+g.Lmstocki+g.Ingstocki+g.Onorderi,
Ballance=g.BBstocki+g.Lmstocki+g.Ingstocki+g.Onorderi=g.Commited
})
.ToList();
}

Related

Unusual StackOverflowException in ListDictionaryInternal

I have class library with a bunch of static methods. While trying to call one of them, I experience unhandled StackOverflowException somewhere in the ListDictionaryInternal class.
I tried enabling .Net Framework (v 4.5.2) stepping, surrounding call with try/catch block, and executing it step by step. When I place continue statement after Appendix A comment, then comment it while debugging, method works as expected. Otherwise I cannot even hit breakpoint at the start at the method. I also tried to call method with all parameters set to null, but it did not help either.
public static List<CalcSector> Split(List<CalcSector> calibration, List<ProfilePoint> profile, List<MeasurementPoint> additionalPoints)
{
double lengthCorridor = 10d;
double lengthEpsilon = 1d;
if (!(calibration?.Any() ?? false)) throw new ArgumentNullException(nameof(calibration), "Empty calibration table");
if (!(profile?.Any() ?? false)) throw new ArgumentNullException(nameof(profile), "Empty profile points collection");
for (int i = 0; i < calibration.Count - 1; i++)
if (Math.Abs(calibration[i].EndDistance - calibration[i + 1].StartDistance) > lengthEpsilon)
throw new ArgumentException($"calibration[{i}]", "Calibration table integrity is compromised");
List<CalcSector> result = new List<CalcSector>();
List<ProfilePoint> SummitPoints = new List<ProfilePoint>();
calibration.ForEach(x => result.Add(x));
profiles = profile.OrderBy(x => x.Distance).ToList();
//
if (additionalPoints?.Any() ?? false)
foreach (MeasurementPoint mp in additionalPoints.Where(x => x.Id != int.MinValue && x.Id != int.MaxValue))
for (int i = 0; i < result.Count; i++)
if (Math.Abs(mp.Distance - result[i].StartDistance) > lengthEpsilon && Math.Abs(mp.Distance - result[i].EndDistance) > lengthEpsilon && mp.Distance > result[i].StartDistance && mp.Distance < result[i].EndDistance)
{
CalcSector c = new CalcSector()
{
StartDistance = mp.Distance,
StartHeight = BinaryHeightSearch(mp.Distance),
StartPointId = mp.Id,
EndDistance = result[i].EndDistance,
EndHeight = result[i].EndHeight,
Length = result[i].EndDistance - mp.Distance,
Thickness = result[i].Thickness,
};
result[i].EndDistance = mp.Distance;
result[i].EndHeight = c.StartHeight;
result[i].EndPointId = mp.Id;
c.Volume = result[i].Volume / result[i].Length * c.Length;
result[i].Length -= c.Length;
result[i].Volume -= c.Volume;
result.Insert(i + 1, c);
break;
}
else if (Math.Abs(mp.Distance - result[i].StartDistance) < lengthEpsilon)
result[i].StartPointId = mp.Id;
else if (Math.Abs(mp.Distance - result[i].EndDistance) < lengthEpsilon)
result[i].EndPointId = mp.Id;
int start = 0;
int end = 0;
bool hasSpikes = true;
while (hasSpikes)
{
hasSpikes = false;
//Appendix A
for (int j = 0; j < result.Count; j++)
{
result[j].z = -1d * (result[j].StartHeight - result[j].EndHeight) / (result[j].EndDistance - result[j].StartDistance);
result[j].sI = start = BinaryProfileSearch(result[j].StartDistance);
result[j].eI = end = BinaryProfileSearch(result[j].EndDistance);
for (int i = start + 1; i < end; i++)
if (Math.Abs(result[j].z * (profiles[i].Distance - result[j].StartDistance) + result[j].StartHeight - profiles[i].Height) > lengthCorridor)
{
int maxIndex = -1;
double maxH = double.MinValue;
int minIndex = -1;
double minH = double.MaxValue;
for (; start < end; start++)
{
if (Math.Abs(result[j].z * (profiles[start].Distance - result[j].StartDistance) + result[j].StartHeight - profiles[start].Height) <= lengthCorridor)
continue;
if (result[j].z * (profiles[i].Distance - result[j].StartDistance) + result[j].StartHeight - profiles[i].Height > maxH)
{
maxH = profiles[start].Height;
maxIndex = start;
}
if (result[j].z * (profiles[i].Distance - result[j].StartDistance) + result[j].StartHeight - profiles[i].Height < minH)
{
minH = profiles[start].Height;
minIndex = start;
}
}
int target = Math.Min(maxIndex, minIndex);
CalcSector c = new CalcSector()
{
StartDistance = profiles[target].Distance,
StartHeight = profiles[target].Height,
sI = target,
EndDistance = result[j].EndDistance,
EndHeight = result[j].EndHeight,
EndPointId = result[j].EndPointId,
eI = result[j].eI,
Length = result[j].EndDistance - profiles[target].Distance,
Thickness = result[j].Thickness,
};
result[j].EndDistance = c.StartDistance;
result[j].EndHeight = c.StartHeight;
result[j].EndPointId = null;
result[j].eI = target;
result[j].z = -1d * (result[j].StartHeight - result[j].EndHeight) / (result[j].EndDistance - result[j].StartDistance);
c.Volume = result[j].Volume / result[j].Length * c.Length;
result[j].Length -= c.Length;
result[j].Volume -= c.Volume;
result.Insert(j + 1, c);
hasSpikes = true;
break;
}
}
}
for (int j = 0; j < result.Count; j++)
{
result[j].Diameter = 1000d * Math.Sqrt(4d * result[j].Volume / Constants["PI"] / result[j].Length);
result[j].OrdNum = j;
}
result.First().StartPointId = int.MinValue;
result.Last().EndPointId = int.MaxValue;
for (int i = 1; i < profiles.Count - 1; i++)
if (profiles[i - 1].Height < profiles[i].Height && profiles[i].Height > profiles[i + 1].Height)
SummitPoints.Add(profiles[i]);
return result;
}
public class CalcSector
{
public int OrdNum;
public double StartDistance;
public double StartHeight;
public int? StartPointId;
public double EndDistance;
public double EndHeight;
public int? EndPointId;
public double Length;
public double Volume;
public double Diameter;
public double Thickness;
public int sI;
public int eI;
public double z;
}
public class ProfilePoint
{
public double Distance;
public double Height;
}
public class MeasurementPoint
{
public int Id;
public double Distance;
}
I expect this method to split some of the original CalcSectors into smaller ones, but all I have is this unhandled fatal exception.
Added:
private static int BinaryProfileSearch(double distance)
{
if (profiles == null || profiles.Count == 0)
return -1;
//assuming that profile points are already ordered by distance
if (distance <= profiles.First().Distance)
return 0;
if (distance >= profiles.Last().Distance)
return profiles.Count - 1;
int first = 0;
int last = profiles.Count - 1;
while (first + 1 < last)
{
int mid = (first + last) / 2;
if (distance <= profiles[mid].Distance)
last = mid;
else
first = mid + 1;
}
if (distance - profiles[first].Distance > profiles[last].Distance - distance)
return last;
else
return first;
}
The solution came quite unexpected: invalid value of 8087 control word. Next line changes it back.
_controlfp(0x9001F, 0xFFFFF);

Knuth Morris Pratt algorithm implementation

I'm trying to implement KMP algorithm. Part "if (W[i] == S[m + i])" returns index out of range exception and I can't get it to work.
I was following example on Wikipedia: https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
static int[] KMPTable(string W)
{
int[] T = new int[W.Length];
int pos = 2;
int cnd = 0;
T[0] = -1;
T[1] = 0;
while (pos < W.Length)
{
if (W[pos - 1] == W[cnd])
{
T[pos] = cnd + 1;
cnd = cnd + 1;
pos = pos + 1;
}
else
if (cnd > 0)
{
cnd = T[cnd];
}
else
{
T[pos] = 0;
pos = pos + 1;
}
}
return T;
}
static int[] KMPSearch(string S, string W)
{
int m = 0;
int i = 0;
int[] kmpNext = KMPTable(S);
List<int> result = new List<int>();
while (m + i < S.Length)
{
if (W[i] == S[m + i])
{
if (i == W.Length - 1)
{
result.Add(m);
}
i = i + 1;
}
else
{
m = m + i - kmpNext[i];
if (kmpNext[i] > -1)
i = kmpNext[i];
else
i = 0;
}
}
return result.ToArray();
}
When m + i < S.Length, then it might be W[i] that is out of its index. Try checking with a step-by-step debug.

How to eliminate repeating code in Sorting methods -C#

Please, help me to eliminate repeating code in "SortMG" and "SortByName" methods. It is basically the same text and it annoys me.
class Student
{
public string name;
public string major;
public double grade;
public string studyForm;
public Student(string name, string major, double grade, string studyForm)
{
this.name = name;
this.major = major;
this.grade = grade;
this.studyForm = studyForm;
}
}
class Program
{
static void SortMG(Student[] sortMG, int n)
{
int i, j;
Student tmpMG = new Student("","", 0, "");
for (i = 0; i < n - 1; i++)
{
for (j = i; j < n; j++)
{
if (sortMG[j].major.CompareTo(sortMG[i].major)<0)
{
//I'm asking about this part:
tmpMG.name = sortMG[j].name;
tmpMG.major = sortMG[j].major;
tmpMG.studyForm = sortMG[j].studyForm;
tmpMG.grade = sortMG[j].grade;
sortMG[j].name = sortMG[i].name;
sortMG[j].major = sortMG[i].major;
sortMG[j].studyForm = sortMG[i].studyForm;
sortMG[j].grade = sortMG[i].grade;
sortMG[i].name = tmpMG.name;
sortMG[i].major = tmpMG.major;
sortMG[i].studyForm = tmpMG.studyForm;
sortMG[i].grade = tmpMG.grade;
}
else if (sortMG[j].major.CompareTo(sortMG[i].major) == 0)
{
if (sortMG[j].grade > sortMG[i].grade)
{
//and this part:
tmpMG.name = sortMG[j].name;
tmpMG.major = sortMG[j].major;
tmpMG.studyForm = sortMG[j].studyForm;
tmpMG.grade = sortMG[j].grade;
sortMG[j].name = sortMG[i].name;
sortMG[j].major = sortMG[i].major;
sortMG[j].studyForm = sortMG[i].studyForm;
sortMG[j].grade = sortMG[i].grade;
sortMG[i].name = tmpMG.name;
sortMG[i].major = tmpMG.major;
sortMG[i].studyForm = tmpMG.studyForm;
sortMG[i].grade = tmpMG.grade;
}
}
}
}
}
static void SortByName(Student[] sortN, int n)
{
int i, j;
Student tmpN = new Student("", "", 0, "");
for (i = 0; i < n - 1; i++)
{
for (j = i; j < n; j++)
{
if (sortN[j].name.CompareTo(sortN[i].name) < 0)
{
//and this part:
tmpN.name = sortN[j].name;
tmpN.major = sortN[j].major;
tmpN.studyForm = sortN[j].studyForm;
tmpN.grade = sortN[j].grade;
sortN[j].name = sortN[i].name;
sortN[j].major = sortN[i].major;
sortN[j].studyForm = sortN[i].studyForm;
sortN[j].grade = sortN[i].grade;
sortN[i].name = tmpN.name;
sortN[i].major = tmpN.major;
sortN[i].studyForm = tmpN.studyForm;
sortN[i].grade = tmpN.grade;
}
}
}
}
}
It looks like you are "swapping" items by swapping their property values. Seems like you should be just swapping the items instead:
if (sortMG[j].grade > sortMG[i].grade)
{
//and this part:
tmpMG = sortMG[j];
sortMG[j] = sortMG[i];
sortMG[i] = tmpMG;
}
You could also move that swap into a function that you call from the three locations to reduce duplicate code further:
public void Swap(Student[] sortMG, int i, int j)
{
//TODO: add bounds/null hecking
var tmpMG = sortMG[j];
sortMG[j] = sortMG[i];
sortMG[i] = tmpMG;
}
You could save yourself a lot of work by using Linq.
For example you could sort a Student[] by Major with the following:
List<Student> students = new List<Student>()
{
new Student("Jose Mendez", "Math", 80, "Beta"),
new Student("Alex Bello", "Math", 90, "Alpha"),
new Student("Bob Junior", "EE", 100, "Charlie")
};
Student[] array = students.ToArray();
array = array.OrderBy(x => x.Major).ToArray();
It seems like you are asking for something like:
static void copyStudent(Student from, Student to)
{
Student tmpMG = new Student();
tmpMG.name = from.name;
tmpMG.major = from.major;
tmpMG.studyForm = from.studyForm;
tmpMG.grade = from.grade;
from.name = to.name;
from.major = to.major;
from.studyForm = to.studyForm;
from.grade = to.grade;
to.name = tmpMG.name;
to.major = tmpMG.major;
to.studyForm = tmpMG.studyForm;
to.grade = tmpMG.grade;
}
static void SortMG(Student[] sortMG, int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
{
for (j = i; j < n; j++)
{
if (sortMG[j].major.CompareTo(sortMG[i].major)<0)
copyStudent(sortMG[j], sortMG[i]);
else if (sortMG[j].major.CompareTo(sortMG[i].major) == 0)
{
if (sortMG[j].grade > sortMG[i].grade)
copyStudent(sortMG[j], sortMG[i]);
}
}
}
}
static void SortByName(Student[] sortN, int n)
{
for (int i = 0; i < n - 1; i++)
for (int j = i; j < n; j++)
if (sortN[j].name.CompareTo(sortN[i].name) < 0)
copyStudent(sortN[j], sortN[i]);
}
why not use:
static void SortMG(Student[] sortMG, int n)
{
sortMG = sortMG.OrderBy(i => i.major).ThenBy(i=> i.grade).ToArray();
}
static void SortByName(Student[] sortN, int n)
{
sortN = sortN.OrderBy(i => i.name).ToArray();
}

Neural Net - Feed Forward, Matrix Multiplication in C#

I'm attempting to make a Neural Network in C#, I based the design in a python code I made a while back. But somehow the end result is not the same.
I'm new to C# and I'm using it in Unity, so I have limitation to library uses.
In python numpy can do matrix multiplications with the numpy.dot() method. I Haven't found something similar in C#, especially in Unity. So I had to do it by hand.
The Python code:
import numpy as np
class NN:
def __init__(self, n_input, n_hidden_layers, n_hidden_nodes, n_output):
self.weights_hidden = []
for n in range(n_hidden_layers + 1):
if n == 0:
size = n_input, n_hidden_nodes
elif n == n_hidden_layers:
size = n_hidden_nodes, n_output
else:
size = n_hidden_nodes, n_hidden_nodes
self.weights_hidden.append(
np.random.random(size)
)
#staticmethod
def activation(x):
return np.tanh(x)
def feed_forward(self, ip):
input_values = (ip - np.mean(ip, axis=0)) / np.std(ip, axis=0)
for w, weights in enumerate(self.weights_hidden):
if w == 0:
result = input_values
result = np.array(
map(self.activation, result.dot(weights))
)
return result
ANN = NN(n_input=5, n_hidden_layers=2, n_hidden_nodes=3, n_output=1)
print ANN.feed_forward([1, 2, 3, 4, 5])
My attempt to convert it to C#.
using UnityEngine;
using System.Collections;
public class neural_net : MonoBehaviour {
int n_inputs;
int n_hidden_layers;
int n_hidden_nodes;
int n_outputs;
float[] inputs;
ArrayList hidden_weights;
ArrayList hidden_results;
float[] output_results;
public void init(int n_inputs, int n_hidden_layers, int n_hidden_nodes, int n_outputs){
this.n_inputs = n_inputs;
this.n_hidden_layers = n_hidden_layers;
this.n_hidden_nodes = n_hidden_nodes;
this.n_outputs = n_outputs;
this.hidden_weights = new ArrayList ();
this.hidden_results = new ArrayList ();
this.output_results = new float[n_outputs];
int rows;
int columns;
for (int h = 0; h < n_hidden_layers + 2; h++) {
if (h == 0){
// input -> hidden
rows = n_inputs;
columns = n_hidden_nodes;
}
else if(h == n_hidden_layers + 1){
// hidden -> output
rows = n_hidden_nodes;
columns = n_outputs;
}
else {
// hidden -> hidden
rows = n_hidden_nodes;
columns = n_hidden_nodes;
}
float[] hidden_result = new float[rows*columns];
hidden_results.Add(hidden_results);
float[,] target = new float[rows,columns];
string test = "";
for(int r = 0; r < rows; r++){
for(int c = 0; c < columns; c++){
target[r,c] = Random.Range(0.0f, 1.0f);
test += target[r,c] + ", ";
}
}
hidden_weights.Add(target);
}
}
float activation(float x){
// tanh(x);
return (1 - Mathf.Exp (-2 * x)) / (1 + Mathf.Exp (-2 * x));
}
float[] _dot_matrix(float[] results, float[,] weights){
float[] new_matrix = new float[weights.GetLength(1)];
string t0 = "";
for (int r = 0; r < weights.GetLength(1); r++){
float res = 0;
for (int c = 0; c < weights.GetLength(0); c++) {
res += results[c] * weights[c,r];
}
new_matrix[r] = res;
}
return new_matrix;
}
float[] _map_activation(float[] pre_results){
float[] results = new float[pre_results.Length];
for (int i = 0; i < results.Length; i++) {
results[i] = activation(pre_results[i]);
}
return results;
}
float[] feed_forward(){
int h;
for (h = 0; h < n_hidden_layers + 2; h++) {
float[] dot_matrix_result;
if(h == 0){
dot_matrix_result = _dot_matrix(inputs, (float[,])hidden_weights[h]);
}
else if (h == n_hidden_layers +1){
dot_matrix_result = _dot_matrix((float[])hidden_results[h-1], (float[,])hidden_weights[h]);
output_results = _map_activation(dot_matrix_result);
break;
}
else {
dot_matrix_result = _dot_matrix((float[])hidden_results[h-1], (float[,])hidden_weights[h]);
}
float[] result = _map_activation(dot_matrix_result);
hidden_results[h] = _map_activation(result);
}
return output_results;
}
float[] normalize_input(float[] inputs){
float sum = 0.0f;
for (int i = 0; i < inputs.Length; i++) {
sum += inputs[i] ;
}
float average = sum / inputs.Length;
float[] deviations = new float[inputs.Length];
for (int i = 0; i < inputs.Length; i++) {
deviations[i] = Mathf.Pow(inputs[i] - average,2);
}
float sum_deviation = 0;
for (int i = 0; i < deviations.Length; i++) {
sum_deviation += deviations[i];
}
float variance = sum_deviation / deviations.Length;
float std = Mathf.Sqrt (variance);
for (int i = 0; i < inputs.Length; i++) {
inputs[i] = (inputs[i] - average)/std;
}
return inputs;
}
public void start_net(float[] inputs){
this.inputs = normalize_input(inputs);
feed_forward ();
}
}
I run the net from other script using the init method and then the start_net() method.
I made a test with not random weights and fixed input data, but it didn't came to the same result as the python code.
What's wrong with the C# code?

In C# arrays, how not to create duplicated random numbers?

I'm a beginner in C#, trying to make a lottery form applicaton.
There are types, first when you have 5 tips ( otos bool ) and 5 tips ( hatos bool ).
And there are many types of how many numbers will be raffled (tiz, harminc, kilencven, negyvenot).
I tried to scan the numbers after the raffle with Array.Equals with this code:
for (int i = 0; i <= 4; i++)
{
for (int y = 0; y <= 4; y++)
{
if (Array.Equals(lottoszamok[i], lottoszamok[y]))
lottoszamok[i] = r.Next (1, ?);
}
}
but at this the number will be scanned with itself too, so it will be always equal.
here is my code by the way:
if (otos == true)
{
for (int i = 0; i <= 5; i++)
{
if (tiz == true)
{
lottoszamok[i] = r.Next(1, 10);
}
else if (harminc == true)
{
lottoszamok[i] = r.Next(1, 30);
}
else if (kilencven == true)
{
lottoszamok[i] = r.Next(1, 90);
}
else if (negyvenot == true)
{
lottoszamok[i] = r.Next(1, 45);
}
else if (egyeni == true)
{
lottoszamok[i] = r.Next(1, (egyeniertek + 1));
}
}
}
if (hatos == true)
{
for (int i = 0; i <= 6; i++)
{
if (tiz == true)
{
lottoszamok[i] = r.Next(1, 10);
}
else if (harminc == true)
{
lottoszamok[i] = r.Next(1, 30);
}
else if (kilencven == true)
{
lottoszamok[i] = r.Next(1, 90);
}
else if (negyvenot == true)
{
lottoszamok[i] = r.Next(1, 45);
}
else if (egyeni == true)
{
lottoszamok[i] = r.Next(1, (egyeniertek + 1));
}
}
}
If you're trying to pick numbers from a range 1..n without repetitions, you need to "shuffle" the numbers out:
int[] allPossibleNumbers = Enumerable.Range(1, maxNumber).ToArray();
int[] picked = new int[numberToPick];
for (int i = 0; i < numberToPick; i++)
{
int index = r.Next(i, maxNumber);
picked[i] = allPossibleNumbers[index];
allPossibleNumbers[index] = allPossibleNumbers[i];
}
where numberToPick is 5 if otos or 6 if hatos, and maxNumber depends on tiz, harminc, kilencven, negyvenot, egyeni and egyeniertek.
If your maxNumber is huge and you only want to pick a few numbers, the following doesn't require the whole range to be in memory at once:
Dictionary<int, int> outOfPlace = new Dictionary<int,int>();
int[] picked = new int[numberToPick];
for (int i = 0; i < numberToPick; i++)
{
int shuffleOut = outOfPlace.ContainsKey(i) ? outOfPlace[i] : i;
int index = r.Next(i, maxNumber);
picked[i] = 1 + (outOfPlace.ContainsKey(index) ? outOfPlace[index] : index);
outOfPlace[index] = shuffleOut;
outOfPlace.Remove(i);
}
Try this one!
if (i!=y && Array.Equals(lottoszamok[i], lottoszamok[y]))
I made it this way, if you want you could put swapping like method.
static void SwapInts(int[] array, int position1, int position2)
{
// Swaps elements in an array.
int temp = array[position1]; // Copy the first position's element
array[position1] = array[position2]; // Assign to the second element
array[position2] = temp; // Assign to the first element
}
static void Main()
{
Random rng = new Random();
int n = int.Parse(Console.ReadLine());
int[] intarray = new int[n];
for (int i = 0; i < n; i++)
{
// Initialize array
intarray[i] = i + 1;
}
// Exchange resultArray[i] with random element in resultArray[i..n-1]
for (int i = 0; i < n; i++)
{
int positionSwapElement1 = i + rng.Next(0, n - i);
SwapInts(intarray, i, positionSwapElement1);
}
for (int i = 0; i < n; i++)
{
Console.Write(intarray[i] + " ");
}
}
}
I spend many time to get this, but i believe i can do it, now it's done, By the Easier way in the word, this kill every think about Random not duplicate,very simply code without any philosophy or difficulty of Developers made ... (welcome to my work) that (BEST OF THE BEST):
Numbers between (1-10) without any duplicate, 1- MY WORK in C#
private void TenNumbersRandomly()
{
int[] a = new int[10];
Random r = new Random();
int x;
for (int i = 0; i < 10; i++)
{
x= r.Next(1, 11);
for (int j = 0; j <= i ; j++)
{
while (a[j] == x)
{
x = r.Next(1, 11);
j = 0;
}
}
a[i] = x;
tb1.Text += a[i]+"\n";
}
}
2- in VB some Different i also have it :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim x As Integer, i As Integer, j As Integer
x = Int(Rnd() * 10) + 1
Label1.Text = ""
Dim a(9) As Integer
For i = 0 To 9
x = Int(Rnd() * 10) + 1
For j = 0 To i
While (a(j) = x)
x = Int(Rnd() * 10) + 1
j = 0
End While
Next j
a(i) = x
Label1.Text += a(i).ToString() + " "
Next i

Categories