Reduce execution time c# algorithm - c#

I'm solving Kattis' bokforing problem and one of the test cases fails due to execution time being too long (> 2 sec). Can anyone give me any advice on how I can improve?
class Program
{
static void Main(string[] args)
{
/* Inputs
3 5
SET 1 7
PRINT 1
PRINT 2
RESTART 33
PRINT 1
*/
string first = Console.ReadLine();
int N = Convert.ToInt32(first.Split(" ")[0]);
int Q = Convert.ToInt32(first.Split(" ")[1]);
int[] Accounts = new int[N];
string[] Operations = new string[Q];
for (int i = 0; i < Operations.Length; i++)
{
Operations[i] = Console.ReadLine();
}
for (int i = 0; i < Operations.Length; i++)
{
string[] op = Operations[i].Split(" ");
string operation = op[0];
int accountId = 0;
int ammont = 0;
if (operation == "SET")
{
accountId = Convert.ToInt32(op[1]);
ammont = Convert.ToInt16(op[2]);
Accounts[accountId - 1] = ammont;
}
if (operation == "PRINT")
{
accountId = Convert.ToInt32(op[1]);
Console.WriteLine(Accounts[accountId - 1]);
}
if (operation == "RESTART")
{
ammont = Convert.ToInt16(op[1]);
for (int j = 0; j <= N - 1; j++)
{
Accounts[j] = ammont;
}
}
}
}
}

First of all I copied recommended IO classes from FAQ to the solution, removed double loop (there is no need to loop twice - reading inputs first and then processing them) and then the main trick was to use Dictionary instead of array so there is no need to manually clear it/set amount to all items in it every time:
var scanner = new Scanner();
using(var writer = new BufferedStdoutWriter())
{
var N = scanner.NextInt();
var Q = scanner.NextInt();
var amount = 0;
var Accounts = new Dictionary<int, int>();
for (var i = 0; i < Q; i++)
{
var s = scanner.Next();
var accountId = 0;
if (s == "SET")
{
accountId = scanner.NextInt();
Accounts[accountId] = scanner.NextInt();
}
else if (s == "PRINT")
{
accountId = scanner.NextInt();
if (!Accounts.TryGetValue(accountId, out var value))
{
value = amount;
}
writer.WriteLine(value);
}
else if (s == "RESTART")
{
amount = scanner.NextInt();
Accounts = new Dictionary<int, int>();
}
}
}

Related

Anagram Decoder is Adding Onto Previous String

so I'm making an Anagram Decoder, and basically, it goes through, picks a unique version of the anagram, and then it adds it to a list and clears it. That way, when it runs through again, if it tries to make that word, it loops back through and tries again. However, when it gets to the end, it adds onto the previous string.
By this I mean if the string was "hey", the first time it might do "yeh", and the second time it'd do "yehhye". It adds on the new one to the end of the last one. This doesn't make sense though since I clear the variables that would store that (except for the one that stores the before anagrams).
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Anagram_Decoder {
class Program {
static void Main(string[] args) {
Random random = new Random();
// Create string, count it, and split it
string anagram = "hey";
int anagramLength = anagram.Length;
int result = anagramLength;
// Find possibilities
for (int i = 1; i < anagramLength; i++) {
result = result * i;
}
int anagramPossibilities = result;
List<string> anagramsFound = new List<string>();
char[] anagramSplit = anagram.ToCharArray();
int[] numbers = new int[anagram.Length];
for (int l = 0; l < anagramPossibilities; l++) {
string endResult = "";
bool failed = false;
while (true) {
numbers = new int[anagram.Length];
for (int i = 0; i < anagram.Length; i++) {
while (true) {
System.Threading.Thread.Sleep(15);
int randomNumber = random.Next(1, anagram.Length + 1);
foreach (int n in numbers) {
if (n == randomNumber && failed == false) {
failed = true;
}
}
if (failed == true) {
failed = false;
continue;
}
else {
numbers[i] = randomNumber;
endResult += randomNumber;
break;
}
}
}
numbers = new int[anagram.Length];
failed = false;
char[] endResultChars = endResult.ToCharArray();
string finalResult = "";
foreach (char i in endResultChars) {
finalResult += anagram[Convert.ToInt32(Convert.ToString(i)) - 1];
}
foreach (string n in anagramsFound) {
if (n == finalResult && failed == false) {
failed = true;
}
}
if (failed == true) {
failed = false;
continue;
}
else {
anagramsFound.Add(finalResult);
finalResult = "";
Console.ReadKey();
}
}
}
Console.ReadKey();
}
}
}

Odd C# behavior

I'm a hobby programmer.
I tried to ask this question earlier on a very unstructured way (Sorry again), now I try to ask on the proper way.
I wrote the following code that seems to work unreliably.
The code was written like this for several reasons. I know it's messy but it should still work. To explain why I wrote it like this would mean that I need to explain several weeks' of work that is quite extensive. Please accept that this is at least the least worse option I could figure out. In the below sample I removed all sections of the code that are not needed to reproduce the error.
What this program does in a nutshell:
The purpose is to check a large number of parameter combinations for a program that receives streaming data. I simulate the original process to test parameter combinations.
First data is read from files that represents recorded streaming data.
Then the data is aggregated.
Then I build a list of parameters to test for.
Finally I run the code for each parameter combination in parallel.
Inside the parallel part I calculate a financial indicator called the bollinger bands. This is a moving average with adding +/- standard deviation. This means the upper line and the lower line should only be equal when variable bBandDelta = 0. However sometimes it happens that CandleList[slot, w][ctr].bollingerUp is equal to CandleList[slot, w][ctr].bollingerDown even when bBandDelta is not 0.
As a result I don't understand how can line 277 kick in. It seems that sometimes the program fails to write to the CandleList[slot, w][ctr]. However this should not be possible because (1) I lock the list and (2) I use ConcurrentBag. Could I have some help please?
Source files are here.
The code is:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace Justfortest
{
class tick : IComparable<tick> //Data element to represent a tick
{
public string disp_name; //ticker ID
public DateTime? trd_date; //trade date
public TimeSpan? trdtim_1; //trade time
public decimal trdprc_1; //price
public int? trdvol_1; //tick volume
public int CompareTo(tick other)
{
if (this.trdprc_1 == other.trdprc_1)
{
return other.trdprc_1.CompareTo(this.trdprc_1); //Return the later item
}
return this.trdprc_1.CompareTo(other.trdprc_1); //Return the earlier item
}
}
class candle : IComparable<candle> //Data element to represent a candle and all chart data calculated on candle level
{
public int id = 0;
public DateTime? openDate;
public TimeSpan? openTime;
public DateTime? closeDate;
public TimeSpan? closeTime;
public decimal open = 0;
public decimal high = 0;
public decimal low = 0;
public decimal close = 0;
public int? volume = 0;
public decimal totalPrice = 0;
public decimal bollingerUp = 0; //Bollinger upper line
public decimal bollingerDown = 0; //Bollinger below line
public int CompareTo(candle other)
{
if (totalPrice == other.totalPrice)
{
return other.totalPrice.CompareTo(totalPrice); //Return the later item
}
return totalPrice.CompareTo(other.totalPrice); //Return the earlier item
}
}
class param : IComparable<param> //Data element represent a trade event signal
{
public int par1;
public int bollPar;
public int par2;
public int par3;
public int par4;
public int par5;
public int par6;
public decimal par7;
public decimal par8;
public decimal par9;
public decimal par10;
int IComparable<param>.CompareTo(param other)
{
throw new NotImplementedException();
}
}
class programCLass
{
void myProgram()
{
Console.WriteLine("Hello");
Console.WindowWidth = 180;
string[] sources = new string[]
{
#"C:\test\source\sourceW1.csv",
#"C:\test\source\sourceW2.csv",
};
List<candle>[] sourceCandleList = new List<candle>[sources.Count()];
List<param> paramList = new List<param>(10000000);
var csvAnalyzer = new StringBuilder();
{
List<tick>[] updatelist = new List<tick>[sources.Count()];
Console.WriteLine("START LOAD");
for (var i = 0; i < sources.Count(); i++)
{
var file = sources[i];
updatelist[i] = new List<tick>();
// ---------- Read CSV file ----------
var reader = new StreamReader(File.OpenRead(file));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
tick update = new tick();
update.disp_name = values[0].ToString();
update.trd_date = Convert.ToDateTime(values[1]);
update.trdtim_1 = TimeSpan.Parse(values[2]);
update.trdprc_1 = Convert.ToDecimal(values[3]);
update.trdvol_1 = Convert.ToInt32(values[4]);
updatelist[i].Add(update);
}
Console.WriteLine(i);
}
Console.WriteLine("END LOAD"); // All files are in the memory
// Aggreagate
Console.WriteLine("AGGREGATE START");
int tickAggr = 500;
for (var w = 0; w < sources.Count(); w++)
{
sourceCandleList[w] = new List<candle>();
List<tick> FuturesList = new List<tick>();
foreach (var update in updatelist[w])
{
tick t = new tick();
t.disp_name = update.disp_name.ToString();
t.trd_date = update.trd_date;
t.trdtim_1 = update.trdtim_1;
t.trdprc_1 = Convert.ToDecimal(update.trdprc_1);
t.trdvol_1 = update.trdvol_1;
// Add new tick to the list
FuturesList.Add(t);
if (FuturesList.Count == Math.Truncate(FuturesList.Count / (decimal)tickAggr) * tickAggr)
{
candle c = new candle();
c.openDate = FuturesList[FuturesList.Count - tickAggr].trd_date;
c.openTime = FuturesList[FuturesList.Count - tickAggr].trdtim_1;
c.closeDate = FuturesList.Last().trd_date;
c.closeTime = FuturesList.Last().trdtim_1;
c.open = FuturesList[FuturesList.Count - tickAggr].trdprc_1;
c.high = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Max().trdprc_1;
c.low = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Min().trdprc_1;
c.close = FuturesList.Last().trdprc_1;
c.volume = FuturesList.GetRange(FuturesList.Count - tickAggr, tickAggr).Sum(tick => tick.trdvol_1);
c.totalPrice = (c.open + c.high + c.low + c.close) / 4;
sourceCandleList[w].Add(c);
if (sourceCandleList[w].Count == 1)
{
c.id = 0;
}
else
{
c.id = sourceCandleList[w][sourceCandleList[w].Count - 2].id + 1;
}
}
}
FuturesList.Clear();
}
Console.WriteLine("AGGREGATE END");
for (var i = 0; i < sources.Count(); i++)
{
updatelist[i].Clear();
}
}
Console.WriteLine("BUILD PARAMLIST");
for (int par1 = 8; par1 <= 20; par1 += 4) // parameter deployed
{
for (int bollPar = 10; bollPar <= 25; bollPar += 5) // parameter deployed
{
for (int par2 = 6; par2 <= 18; par2 += 4) // parameter deployed
{
for (int par3 = 14; par3 <= 20; par3 += 3) // parameter deployed
{
for (int par4 = 10; par4 <= 20; par4 += 5) // parameter deployed
{
for (int par5 = 4; par5 <= 10; par5 += 2) // parameter deployed
{
for (int par6 = 5; par6 <= 30; par6 += 5)
{
for (decimal par7 = 1.0005M; par7 <= 1.002M; par7 += 0.0005M)
{
for (decimal par8 = 1.002M; par8 <= 1.0048M; par8 += 0.0007M)
{
for (decimal par9 = 0.2M; par9 <= 0.5M; par9 += 0.1M)
{
for (decimal par10 = 0.5M; par10 <= 2; par10 += 0.5M)
{
param p = new param();
p.par1 = par1;
p.bollPar = bollPar;
p.par2 = par2;
p.par3 = par3;
p.par4 = par4;
p.par5 = par5;
p.par6 = par6;
p.par7 = par7;
p.par8 = par8;
p.par9 = par9;
p.par10 = par10;
paramList.Add(p);
}
}
}
}
}
}
}
}
}
}
}
Console.WriteLine("END BUILD PARAMLIST, scenarios to test:{0}", paramList.Count);
var sourceCount = sources.Count();
sources = null;
Console.WriteLine("Start building pools");
int maxThreads = 64;
ConcurrentBag<int> pool = new ConcurrentBag<int>();
List<candle>[,] CandleList = new List<candle>[maxThreads, sourceCount];
for (int i = 0; i <= maxThreads - 1; i++)
{
pool.Add(i);
for (int w = 0; w <= sourceCount - 1; w++)
{
CandleList[i, w] = sourceCandleList[w].ConvertAll(p => p);
}
}
Console.WriteLine("End building pools");
int pItemsProcessed = 0;
Parallel.ForEach(paramList,
new ParallelOptions { MaxDegreeOfParallelism = maxThreads },
p =>
{
int slot = 1000;
while (!pool.TryTake(out slot));
var bollPar = p.bollPar;
decimal bollingerMiddle = 0;
double bBandDeltaX = 0;
for (var w = 0; w < sourceCount; w++)
{
lock (CandleList[slot, w])
{
for (var ctr = 0; ctr < CandleList[slot, w].Count; ctr++)
{
CandleList[slot, w][ctr].bollingerUp = 0; //Bollinger upper line
CandleList[slot, w][ctr].bollingerDown = 0; //Bollinger below line
//Bollinger Bands Calculation
if (ctr + 1 >= bollPar)
{
bollingerMiddle = 0;
bBandDeltaX = 0;
for (int i = 0; i <= bollPar - 1; i++)
{
bollingerMiddle = bollingerMiddle + CandleList[slot, w][ctr - i].totalPrice;
}
bollingerMiddle = bollingerMiddle / bollPar; //average
for (int i = 0; i <= bollPar - 1; i++)
{
bBandDeltaX = bBandDeltaX + (double)Math.Pow(System.Convert.ToDouble(CandleList[slot, w][ctr - i].totalPrice) - System.Convert.ToDouble(bollingerMiddle), 2);
}
bBandDeltaX = bBandDeltaX / bollPar;
decimal bBandDelta = (decimal)Math.Sqrt(System.Convert.ToDouble(bBandDeltaX));
CandleList[slot, w][ctr].bollingerUp = bollingerMiddle + 2 * bBandDelta;
CandleList[slot, w][ctr].bollingerDown = bollingerMiddle - 2 * bBandDelta;
if (CandleList[slot, w][ctr].bollingerUp == CandleList[slot, w][ctr].bollingerDown)
{
Console.WriteLine("?! Items processed=" + pItemsProcessed + " bollPar=" + bollPar + " ctr=" + ctr + " bollingerMiddle=" + bollingerMiddle + " bBandDeltaX=" + bBandDeltaX + " bBandDelta=" + bBandDelta + " bollingerUp=" + CandleList[slot, w][ctr].bollingerUp + " bollingerDown=" + CandleList[slot, w][ctr].bollingerDown);
}
}
// REMOVED Further calculations happen here
}
// REMOVED Some evaluations happen here
}
}
// REMOVED Some more evaluations happen here
Interlocked.Increment(ref pItemsProcessed);
pool.Add(slot);
});
}
static void Main(string[] args)
{
var P = new programCLass();
P.myProgram();
}
}
}

C# Dynamic Arrays and its Calculation

I have 2 dynamic textboxes which stores users input in the form of an array Int32[] iA1 = new Int32[3];
and also have a combo box, which has mathematical operator.
My question is how to get the following output when user fills the number of rows and column dynamically at run time and make an appropriate selection from the combo box.
Thanks in advanceenter image description here
string output = "";
Int32[] array = new Int32[3] { 25, 4, 1 };
int rows = array[0];
int cols = array[1];
int op = array[2];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
int value = 0;
string opStr = "";
if (op == 1) // +
{
opStr = "+";
value = r + c;
}
else if (op == 2) // -
{
opStr = "-";
value = r - c;
}
else if (op == 3) // *
{
opStr = "*";
value = r * c;
}
// ...
output += string.Format("{0} {1} {2} = {3}\t", r, opStr, c, value);
}
output += System.Environment.NewLine;
}
System.Console.Write(output);
System.Diagnostics.Debug.Write(output);
textarea.Text = output;
Here is a small console app which does what you want:
class Program
{
static void Main(string[] args)
{
var firstNumber = 24;
var secondNumber = 4;
var op = "+";
var result = new List<List<string>>();
for (int i = 0; i <= firstNumber; i++)
{
var list = new List<string>();
for (int j = 0; j < secondNumber; j++)
{
list.Add(i.ToString());
list.Add(op);
list.Add(j.ToString());
list.Add("=");
list.Add((i + j).ToString());
}
result.Add(list);
}
foreach (var item in result)
{
Console.WriteLine(string.Join(" ", item));
}
Console.ReadLine();
}
}
You need to take the numbers and the operator from your textboxes.

Searching list by LastIndex in loop.

I am trying to complete an algorithm that adds ProcTime to a max of two other max values (JobNumMax and WSMax). I am having trouble using the FindLastIndex and FindLast in my loops.
Here is my code.
public class JobListOrder
{
public int JobNum { get; set; }
public string Workstation { get; set; }
public int Sequence { get; set; }
public int ProcTime { get; set; }
public int EndHour { get; set; }
public DateTime DueDate { get; set; }
public int Priority { get; set; }
}
Putting into list.
//New List
List<JobListOrder> list = new List<JobListOrder>();
using (StreamReader sr = new StreamReader("C:\\Users\\Nathan\\Documents\\Visual Studio 2013\\Projects\\PubsExample\\PubsExample\\JobsList.txt"))
{
//Add .txt to List
while (sr.Peek() >= 0)
{
string str;
string [] strArray;
str = sr.ReadLine();
strArray = str.Split(',');
JobListOrder currentjob = new JobListOrder();
currentjob.JobNum = int.Parse(strArray[0]);
currentjob.Workstation = strArray[1];
currentjob.Sequence = int.Parse(strArray[2]);
currentjob.ProcTime = int.Parse(strArray[3]);
currentjob.EndHour = int.Parse(strArray[4]);
currentjob.DueDate = DateTime.Parse(strArray[5]);
currentjob.Priority = int.Parse(strArray[6]);
list.Add(currentjob);
}
Sort into a particular way to start calculations
//Job Sort
var ListSort = from jobsort in list
orderby jobsort.Sequence ascending, jobsort.Priority descending, jobsort.DueDate ascending, jobsort.JobNum ascending
select jobsort;
List<JobListOrder> SortList = new List<JobListOrder>(ListSort);
Here is a slight attempt at it
//foreach (var i in SortList)
//{
// if (JobNumMax >= WSMax)
// {
// return i.EndHour = JobNumMax + i.ProcTime;
// }
// else
// return i.EndHour = WSMax + currentjob.ProcTime;
// for (var j = 0; j < SortList.Count; j++)
// {
// int JobLNumMaxIndex = SortList.FindLastIndex(i.JobNum)
// int JobNumMax = i.EndHour[JobNumMaxIndex];
// for (var k = 0; k < SortList.Count; k++)
// {
// int WSMaxIndex = SortList.FindLastIndex(i.Workstation);
// int WSMax = i.EndHour[JobNumMaxIndex];
// }
// }
//}
I am trying to find the LastIndex of a query and return a value of that particular index. I'll try to explain what I mean in the code below Searching for JobNum = 1 and Workstation = Milling with a ProcTime of 1
foreach (var i in SortList) //Iterate through SortList
{
if (JobNumMax (3) >= WSMax (4))
{
return i.EndHour = JobNumMax (3) + i.ProcTime (1); //assigns calculation to EndHour of current record
}
else
return i.EndHour = WSMax (4) + i.ProcTime (1);
for (var j = 0; j < SortList.Count; j++)
{
int JobLNumMaxIndex = SortList.FindLastIndex(1) //Finds last record with JobNum = 1
int JobNumMax = i.EndHour[JobNumMaxIndex];//Return what EndHour is at the index from JobNumMaxIndex search// Lets say 3
for (var k = 0; k < SortList.Count; k++)
{
int WSMaxIndex = SortList.FindLastIndex(Milling);//Finds last record with Workstation = Milling
int WSMax = i.EndHour[JobNumMaxIndex];//Return what EndHour is at the index from WSMaxIndex search// Lets say 4
}
}
}
Result would be 4 + 1 = 5.
I am having trouble with syntax of the algorithm. I can't get the FindLast to work at all.
It looks like you might just be having trouble with the LINQ syntax.
FindLastIndex will take a Predicate<JobListOrder> as an argument, i.e, a function which takes a JobListOrder as an input an returns true or false.
So instead of SortList.FindLastIndex(i.JobNum) you should probably have something like:
SortList.FindLastIndex(order => order.JobNum == i.JobNum);
Corrected in your code:
int JobNumMax = 0;
int WSMax 0;
foreach (var i in SortList)
{
if (JobNumMax >= WSMax)
{
return i.EndHour = JobNumMax + i.ProcTime;
}
else if (JobNumMax > 0 && WSMax > 0)
{
return i.EndHour = WSMax + currentjob.ProcTime;
}
for (var j = 0; j < SortList.Count; j++)
{
int JobLNumMaxIndex = SortList.FindLastIndex(order => order.JobNum == i.JobNum);
JobNumMax = i.EndHour[JobNumMaxIndex];
for (var k = 0; k < SortList.Count; k++)
{
int WSMaxIndex = SortList.FindLastIndex(order => order.Workstation == i.Workstation);
WSMax = i.EndHour[JobNumMaxIndex];
}
}
}

Having result even by non exist inputs

I have a text file data set with following format (the separation character is tab).
0 762354
1 645645
2 4356743
3 576899063
4 64378
.....
that I read it and save it in array by:
for (int klk = 0; klk <= 92159; klk++)
{
lineuserori = fileuserori.ReadLine();
if (!string.IsNullOrEmpty(lineuserori))
{
string[] valuesiesi = lineitemori.Split('\t');
int useridori;
foreach (string value in valuesiesi)
{
useridori = Convert.ToInt32(valuesiesi[1]);
d[klk] = useridori;
}
}
}
NOW, I want to read an input and search for it in array d, if the number exist in array, I do my calculation, if it is not in array show MessageBox.Show("Error");, the problem is, it always show output with every input (even the input does not exist in array) and never show MessageBox.Show("Error");
{
int sc = Convert.ToInt32(txtbx_id.Text);
int n = Convert.ToInt32(txtbx_noofrecomm.Text);
for (int yu = 0; yu <= 92161; yu++)
{
int wer = d[yu];
if (wer == sc)
{
userseq = yu;
break;
}
}
if (userseq >= 0 && userseq <= 92161)
{
var results = new List<float>(1143600);
for (int z = 0; z < 1143600; z++)
{
results.Add(dotproduct(userseq, z));
}
var sb1 = new StringBuilder();
foreach (var resultwithindex in results.Select((r, index) => new { result = r, Index = index }).OrderByDescending(r => r.result).Take(n))
{
sb1.AppendFormat(CultureInfo.InvariantCulture, "{0}: {1}", c[resultwithindex.Index], resultwithindex.result);
sb1.AppendLine();
}
MessageBox.Show(sb1.ToString());
}
if (userseq < 0 || userseq > 92161)
{
MessageBox.Show("Error");
}
}
Any idea
Thanks
In your code to create array , is lineitemori right?
I think, it should be lineuserori.
Replace this:
string[] valuesiesi = lineitemori.Split('\t');
with:
string[] valuesiesi = lineuserori.Split('\t');
I wrote code below. (some lines uses unknown variables commented out)
Input 762354 to txtbx_id and click button1 then empty MessageBox appeared.
Input 76235 to txtbx_id and click button1 then MessageBox say 'Error'.
public partial class Form1 : Form {
// form have three controls txtbx_id, txtbx_noofrecomm and button1.
int[] d = new int[92162];
string data =
"0\t762354\n"
+"1\t645645\n"
+"2\t4356743\n"
+"3\t576899063\n"
+"4\t64378\n";
public Form1() {
InitializeComponent();
using (var fileuserori = new StringReader(data)) { // use StringReader instead of StreamReader
string lineuserori = "";
for (int klk = 0; klk <= 92159; klk++) {
lineuserori = fileuserori.ReadLine();
if (!string.IsNullOrEmpty(lineuserori)) {
// string[] valuesiesi = lineitemori.Split('\t');
string[] valuesiesi = lineuserori.Split('\t');
int useridori;
foreach (string value in valuesiesi) {
useridori = Convert.ToInt32(valuesiesi[1]);
d[klk] = useridori;
}
}
}
}
}
private void button1_Click(object sender, EventArgs e) {
var userseq = -1;
int sc = Convert.ToInt32(txtbx_id.Text);
int n = Convert.ToInt32(txtbx_noofrecomm.Text);
for (int yu = 0; yu <= 92161; yu++) {
int wer = d[yu];
if (wer == sc) {
userseq = yu;
break;
}
}
if (userseq >= 0 && userseq <= 92161) {
var results = new List<float>(1143600);
for (int z = 0; z < 1143600; z++) {
// results.Add(dotproduct(userseq, z));
}
var sb1 = new StringBuilder();
foreach (var resultwithindex in results.Select((r, index) => new { result = r, Index = index }).OrderByDescending(r => r.result).Take(n)) {
// sb1.AppendFormat(CultureInfo.InvariantCulture, "{0}: {1}", c[resultwithindex.Index], resultwithindex.result);
// sb1.AppendLine();
}
MessageBox.Show(sb1.ToString());
}
if (userseq < 0 || userseq > 92161) {
MessageBox.Show("Error");
}
}
}

Categories