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");
}
}
}
Related
Give two strings of equal size. Determine whether each character in the first string can be uniquely replaced by a character in the second string so that the two strings are equal. Display also the corresponding character pairs between the two strings. The code works well now.
Example 1:
For input data:
aab
ttd
The console will display:
True
a => t
b => d
Example 2:
For input data:
tab
ttd
The console will display:
False
In the second example the answer is false because there is no unique correspondence for the character 'a': both 't' and 'd' correspond to it.
This is my code:
using System;
namespace problemeJM
{
class Program
{
static void Main(string[] args)
{
string firstPhrase = Convert.ToString(Console.ReadLine());
string secondPhrase = Convert.ToString(Console.ReadLine());
string aux1 = string.Empty, aux2 = string.Empty;
bool x = true;
for (int i = 0; i < firstPhrase.Length; i++)
{
if (!aux1.Contains(firstPhrase[i]))
{
aux1 += firstPhrase[i];
}
}
for (int i = 0; i < secondPhrase.Length; i++)
{
if (!aux2.Contains(secondPhrase[i]))
{
aux2 += secondPhrase[i];
}
}
if (aux1.Length != aux2.Length)
{
Console.WriteLine("False");
}
else
{
for (int i = 0; i < firstPhrase.Length - 2; i++)
{
for (int j = 1; j < secondPhrase.Length - 1; j++)
{
if (firstPhrase[i] == firstPhrase[j] && secondPhrase[i] == secondPhrase[j])
{
x = true;
}
else if (firstPhrase[i] != firstPhrase[j] && secondPhrase[i] != secondPhrase[j])
{
x = true;
}
else if (firstPhrase[i] == firstPhrase[j] && secondPhrase[i] != secondPhrase[j])
{
x = false;
break;
}
else if (firstPhrase[i] != firstPhrase[j] && secondPhrase[i] == secondPhrase[j])
{
x = false;
break;
}
}
}
Console.WriteLine(x);
aux1 = string.Empty;
aux2 = string.Empty;
if (x == true)
{
for (int i = 0; i < firstPhrase.Length; i++)
{
if (!aux1.Contains(firstPhrase[i]))
{
aux1 += firstPhrase[i];
}
}
for (int i = 0; i < secondPhrase.Length; i++)
{
if (!aux2.Contains(secondPhrase[i]))
{
aux2 += secondPhrase[i];
}
}
for (int i = 0; i <= aux1.Length - 1; i++)
{
for (int j = 1; j <= aux2.Length; j++)
{
if (aux1[i] == aux1[j] && aux2[i] == aux2[j])
{
Console.WriteLine(aux1[i] + " => " + aux2[i]);
break;
}
else if (aux1[i] != aux1[j] && aux2[i] != aux2[j])
{
Console.WriteLine(aux1[i] + " => " + aux2[i]);
break;
}
}
}
}
}
}
}
}
I think you should use a Dictionary<char, char> as commented. But you need to check if there's a unique mapping in both string, so from s1 to s2 and from s2 to s1:
static bool UniqueMapping(string s1, string s2)
{
int length = Math.Min(s1.Length, s2.Length);
var dict = new Dictionary<char, char>(length);
for (int i = 0; i < length; i++)
{
char c1 = s1[i];
char c2 = s2[i];
bool contained = dict.TryGetValue(c1, out char c);
if (contained && c2 != c)
{
return false;
}
dict[c1] = c2;
}
return true;
}
Here are your samples. Note that i use UniqueMapping twice(if true after 1st):
static void Main(string[] args)
{
var items = new List<string[]> { new[]{ "aab", "ttd" }, new[] { "tab", "ttd" }, new[] { "ala bala portocala", "cuc dcuc efghficuc" }, new[] { "ala bala portocala", "cuc dcuc efghijcuc" } };
foreach (string[] item in items)
{
bool result = UniqueMapping(item[0], item[1]);
if(result) result = UniqueMapping(item[1], item[0]);
Console.WriteLine($"Word 1 <{item[0]}> Word 2 <{item[1]}> UniqueMapping? {result}");
}
}
.NET Fiddle: https://dotnetfiddle.net/4DtIyH
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>();
}
}
}
I have a list of clauses in my database and a listview in my custom pane in VSTO.
When I select or drag and drop a list item, it gets copied twice. I found this answer.
Listview ItemSelectionChanged fires twice?
But I dont have a isSelected method for my EventArgs e.
Below is my code, please help me out, I want the data/text to be copied only once.
private void clauseList_SelectedIndexChanged(object sender, EventArgs e)
{
ListView.SelectedListViewItemCollection col = clauseList.SelectedItems;
string temp = clauseList.FocusedItem.Text;
clauseList.DoDragDrop(temp, DragDropEffects.Move);
Microsoft.Office.Interop.Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
Microsoft.Office.Interop.Word.Range range = currentSelection.Range;
currentSelection.TypeText(temp);
currentSelection.TypeParagraph();
clslst(select);
}
public void clslst(object s)
{
DataAccess data = new DataAccess();
List<ClauseDetails> details = new List<ClauseDetails>();
details.AddRange(data.ClausesRelated(s));
string FromtextFromDoc;
FromtextFromDoc = Globals.ThisAddIn.Application.Selection.Text;
Microsoft.Office.Interop.Word.Document docs = Globals.ThisAddIn.Application.ActiveDocument;
List<string> clslist = new List<string>();
string aa = "";
int f = 0;
string tempindex = "";
foreach (Paragraph paragraph in docs.Paragraphs)
{
Style style = paragraph.get_Style() as Style;
string styleName = style.NameLocal;
//var sty = style.Font;
//fontstyle = sty.Name;
//fontsize = sty.Size;
if (styleName.Equals("Heading 1"))
{
f += 1;
if (f == 2)
{
tempindex = aa;
f = 0;
clslist.Add(tempindex);
aa = "";
}
}
if (f > 0)
{
aa += paragraph.Range.Text;
}
}
clslist.Add(aa);
List<string> ClausesNotPresent = new List<string>();
List<string> ClausesPresent = new List<string>();
for (int i = 0; i < clslist.Count; i++)
{
for (int j = 0; j < details.Count; j++)
{
if (clslist[i].Contains(details[j].clausetitle) || clslist[i].Contains(details[j].clause))
{
ClausesPresent.Add(details[j].clausetitle + "\n" + details[j].clause);
}
}
}
List<string> test = new List<string>();
for (int z = 0; z < details.Count; z++)
{
test.Add(details[z].clausetitle + "\n" + details[z].clause);
}
if (ClausesPresent.Count < details.Count)
{
ClausesNotPresent.AddRange(test.Except(ClausesPresent));
}
for(int m=0;m<ClausesNotPresent.Count;m++)
{
ClausesNotPresent[m] = "\n"+ ClausesNotPresent[m];
}
clauseList.Clear();
for (int i = 0; i < ClausesNotPresent.Count; i++)
{
clauseList.Items.Add(ClausesNotPresent[i]);
}
}
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.
As question indicates this is what I am trying to do can anyone see how been fiddling with it for a while. Currently it only shows the first 3 numbers in the text file, when I press the nextButton I want it to go to the next 3 but it does not seem to be working..
namespace GPSProject
{
public partial class Form1 : Form
{
private int count;
internal dataPoints myDataPoints;
public Form1()
{
myDataPoints = new dataPoints();
InitializeComponent();
}
private void buttonNext_Click(object sender, EventArgs e)
{
{
Button b = (Button)sender;
if (b.Name.Equals("buttonNext"))
{
count++;
if (count == (myDataPoints.Count))
count = 0;
}
else
{
count--;
if (count < 0)
count = myDataPoints.Count - 1;
}
dataPoint a = myDataPoints.getItem(count);
textBoxLatitude.Text = a.CurLatitude;
textBoxLongtitude.Text = a.CurLongtitude;
textBoxElevation.Text = a.CurElevation;
}
}
}
}
Above is my forms window and below is my dataPoints
namespace GPSProject
{
class dataPoints
{
public int Count { get { return Points.Count; } }
List<dataPoint> Points;
//string p;
public dataPoints(/*string path*/)
{
Points = new List<dataPoint>();
// p = path;
TextReader tr = new StreamReader(/*p*/"C:/Test.txt");
string input;
while ((input = tr.ReadLine()) != null)
{
string[] bits = input.Split(',');
dataPoint a = new dataPoint(bits[0], bits[1], bits[2]);
Points.Add(a);
}
tr.Close();
}
internal dataPoint getItem(int p)
{
if (p < Points.Count)
{
return Points[p];
}
else
return null;
}
}
}
You'll need to update your while loop to take your data items 3 at a time, something like this:
while ((input = tr.ReadLine()) != null)
{
string[] bits = input.Split(',');
for (int i = 0; i < bits.Length / 3; i++)
{
dataPoint a = new dataPoint(bits[3*i], bits[3*i+1], bits[3*i+2]);
Points.Add(a);
}
}
string input = "1,2,3,4,5,6,7,8,9,10,11,12";
//string input = File.ReadAllText(/*p*/"C:/Test.txt");
List<List<string>> all = input.Split(',')
.Select((s, i) => new { s, i })
.GroupBy(x => x.i / 3)
.Select(g => g.Select(x=>x.s).ToList())
.ToList();
foreach(var bits in all)
{
Console.WriteLine("{0} {1} {2}", bits[0], bits[1], bits[2]);
//dataPoint a = new dataPoint(bits[0], bits[1], bits[2]);
//Points.Add(a);
}
This would give an output
1 2 3
4 5 6
7 8 9
10 11 12