C# Dictionary doesn't find the key after being added - c#

I've made a simple program that will read functions in a text file splitted by a new line and execute it just like a programming language. Here's the code:
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
namespace My_Project
{
class Program
{
public static Dictionary<string, string> variables = new Dictionary<string, string>();
static void Main(string[] args)
{
//string code = args[0];
string code = File.ReadAllText(#"TEXT FILE LOCATION HERE");
var lines = code.Split('\n');
foreach (string line in lines)
{
char[] lineInCharArray = line.ToCharArray();
if (lineInCharArray[0] == '-')
{
string variablename = (lineInCharArray[1]).ToString();
string value = line.Replace("-" + variablename, "");
Console.WriteLine("VARIABLE DEFINED: " + variablename + " - " + value);
variables.Add(variablename, value);
}
if (lineInCharArray[0] == '*')
{
if (lineInCharArray[1] == '*')
{
try
{
string requestedVariable = line.Replace("**", "");
Console.WriteLine("REQUESTED VARIABLE: " +
requestedVariable);
string printedValue = variables[requestedVariable];
Console.WriteLine(printedValue);
}
catch
{
Console.WriteLine("ERROR: ");
List<string> hhh = variables.Keys.ToList();
foreach (string item in hhh)
{
Console.WriteLine("--: " + item);
}
}
}
else
{
string printedValue = line.Replace("*", "");
Console.WriteLine(printedValue);
}
}
if (lineInCharArray[0] == '+')
{
string variable = variables[lineInCharArray[1].ToString()];
Int32 variableInInt = Convert.ToInt32(variable);
Int32 incrementation = Convert.ToInt32(line.Replace("+" + variable, ""));
for (int i = 0; i < incrementation + 1; i++)
{
variableInInt++;
}
variables[lineInCharArray[1].ToString()] = variableInInt.ToString();
}
}
Console.ReadLine();
}
}
}
Input (text file)
-a12 // Set a variable named 'a' and set the value to 12
-j8 // Set a variable named 'j' and set the value to 8
**j // Print the value of the variable of 'j'
**a // Print the value of the variable of 'a'
Problem:
The code outputs the following:
VARIABLE DEFINED: a - 12
VARIABLE DEFINED: j - 8
REQUESTED VARIABLE: j
ERROR:
--: a
--: j
REQUESTED VARIABLE: a
12
The code successfully assigned a to 12 and j to 8, but fails to print j (a is fine though). It says that the key j wasn't found on the dictionary even though the program did add j. The solution should output the following:
VARIABLE DEFINED: a - 12
VARIABLE DEFINED: j - 8
REQUESTED VARIABLE: j
8
REQUESTED VARIABLE: a
12

After the question I asked in a comment, and the answer you posted in a comment, it is obvious that what you have is a line feed character (\r) at the end of j, so what appears to be "j" is not exactly "j"; instead, it is "j\r".
So, you need to clean each line that you read from your file from control characters. In fact, you should clean them from any character which is not part of a valid identifier.

Related

Elements in array (when reproduced from a dictionary value) are reversed

My goal is to make a math expression interpreter with c#, for example if you type "A=3", it'll save the A as a dictionary key and 3 as its value, this program has more features so if you type "B=3" and then "A=B+3" and then "Show(A)", it must display "6" as the answer.
Everything is right until I type something like "A=10" "B=10" "C=A+B" and finally "Show(C)", because Variables' value are 2-digit (or more) numbers in this case, when producing the final result, numbers are saved in the string like "01+01" instead of "10+10" (because A and B values are 10 so A+B should be 10+10), so it's kinda reversed.
I tried to reverse the string and then evaluate the answer but that didn't work as well, simply it gives me "1+1" for some reason!
Notes:
expression evaluation is done by "return Convert.ToInt32(new DataTable().Compute(result, null));"
because strings are immutable in c#, when every expression like "A+B" or "3+5" comes in the method, I create a new empty string like (string result = " ";) and then with the help of "result = ValidExpression[i] + result.Remove(counter, 0);", I change the variables with values (note = if all the elements of input are numbers, answer is right) like "A" with "23" and put them in the new string and then evaluate the final string. But as I said, it saves the 23 as 32 so the answer will be wrong.
This is my code and the bug is probably in the LongProcessing method.
Thanks for your helps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Data;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome To The Program\nCorrect Syntax:");
Console.WriteLine("A=10\nB=15\nC=A+B\nD=13/4-2+A-C+B\nShow(D)");
Console.WriteLine("\nEnter your input:");
Expression E = new Expression();
string expression = "start";
while (expression != "exit")
{
expression = Console.ReadLine();
// for show command
if (expression.Contains("Show") == true)
try { E.Show(expression[5]); }
catch (Exception e)
{
Console.WriteLine("input is not correct, Can not show anything. please try again");
}
if (E.Validation(expression) == false)
Console.WriteLine("input is not correct, please try again");
else
E.Processing(expression);
}
Console.ReadKey();
}
}
class Expression
{
public Dictionary<Char, String> Variables = new Dictionary<Char, String>();
public Expression()
{ }
public Boolean Validation(string expression)
{
// true if c is a letter or a decimal digit; otherwise, false && true if c is a decimal digit; otherwise, false.
if (!Char.IsLetterOrDigit(expression[0]) || Char.IsDigit(expression[0]))
return false;
else
return true;
}
public void Processing(String ValidExpression)
{
// Update Dictionary with new values per key
if (Variables.ContainsKey(ValidExpression[0]))
Variables.Remove(ValidExpression[0]);
string temp = " ";
if (ValidExpression.Length > 2 && !ValidExpression.Contains("Show") && !ValidExpression.Contains("exit"))
{
// removing the variable name and "=" from the string
for (int i = 2; i < ValidExpression.Length; i++)
temp = ValidExpression[i] + temp.Remove(i, 0);
Variables.Add(ValidExpression[0], LongProcessing(temp).ToString());
}
}
// something is wrong in this method
public int LongProcessing(String ValidExpression)
{
string temp;
int counter = 0;
string result = " ";
for (int i = 0; i < ValidExpression.Length; i++)
{
//changing variables (letters) with values
if (Char.IsLetter(ValidExpression[i]))
{
if (Variables.ContainsKey(ValidExpression[i]))
{
Variables.TryGetValue(ValidExpression[i], out temp);
for (int j = 0; j < temp.Length; j++)
{
result = temp[j] + result.Remove(counter, 0);
counter++;
}
}
}
else
{
result = ValidExpression[i] + result.Remove(counter, 0);
counter++;
}
}
// checks if all of the string elements are numbers
if (ValidExpression.All(char.IsDigit))
return Convert.ToInt32(ValidExpression);
else
{
return Convert.ToInt32(new DataTable().Compute(result, null));
}
}
public void Show(Char ValidExpression)
{
Console.WriteLine(Variables[ValidExpression]);
}
}
}
This is broken:
for (int i = 2; i < ValidExpression.Length; i++)
temp = ValidExpression[i] + temp.Remove(i, 0);
temp.Remove(i, 0) is a non op, you might as well just write temp
So let's plot the loop:
Assume ValidExpression is "A=10"
Temp starts out as " "
First iteration, temp is "1 "
Second iteration, temp is "01 "
Any operation that works left to right through a string, character by character, pulling a character out and sticking it on the start of a growing string, will reverse the string
Perhaps you meant to not have a loop and instead do temp = ValidExpression.Substring(2) ?
Here are some suggestions:
Start by looking at the value of "temp" in "Processing". To assist in your debugging, add a "Console.WriteLine" statement.
public void Processing(String ValidExpression)
{
// Update Dictionary with new values per key
if (Variables.ContainsKey(ValidExpression[0]))
Variables.Remove(ValidExpression[0]);
string temp = " ";
if (ValidExpression.Length > 2 && !ValidExpression.Contains("Show") && !ValidExpression.Contains("exit"))
{
// removing the variable name and "=" from the string
for (int i = 2; i < ValidExpression.Length; i++)
{
temp = ValidExpression[i] + temp.Remove(i, 0);
Console.WriteLine(" temp: " + temp); //added for debugging
}
Variables.Add(ValidExpression[0], LongProcessing(temp).ToString());
}
}
A couple of other things:
The user is never informed how to exit.
There is a class named "Expression" and a string variable named
"expression". This is likely to cause confusion.
You may also want to look at this post: how to convert a string to a mathematical expression programmatically

Can't get my method to upper case my string arrays

The whole program is listed after, but the only problem i have with it is the ToUppers() method. I just want this method to iterate over each string in my array, and then make everything upper case.
private static string[] ToUppers(string[] stringToUpperArrays)
{
string stringer;
foreach (string value in stringToUpperArrays)
{
stringer = value.ToUpper(); // <== this line highlighted
Console.WriteLine(stringer);
}
return stringToUpperArrays;
}
The program executes after it prints it on the console, and it lists a NullReferenceException, and highlights the stringer = value.ToUpper(); line
The whole program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utility;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//Mark Bouwman
//CNT A01
//ICA18
//April 2nd
string answer;
int numInArray;
string[] stringArrays;
string[] stringArraysToDisplay;
string[] stringToUpperArrays;
//TITLE
Console.WriteLine("\t\tStringy");
do
{
numInArray = Utility.Utility.GetInt(2, 10, "Enter the size of the array from 2 to 10: ");
stringArrays = CreateArray(numInArray);
stringArraysToDisplay = Display(stringArrays);
stringToUpperArrays = ToUppers(stringArrays);
//aksing to run program again
Console.Write("Run program again? yes or no: ");
answer = Console.ReadLine();
}
while (answer.Equals("yes", StringComparison.CurrentCultureIgnoreCase));
}
private static string[] CreateArray(int numInArray)
{
int index;
string[] stringArray;
stringArray = new string[(numInArray + 1)];
for (index = 0; index < numInArray; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
return stringArray;
}
private static string[] Display(string[] stringArraysDisplay)
{
foreach (string value in stringArraysDisplay)
{
Console.WriteLine(value);
}
return stringArraysDisplay;
}
private static string[] ToUppers(string[] stringToUpperArrays)
{
string stringer;
foreach (string value in stringToUpperArrays)
{
stringer = value.ToUpper();
Console.WriteLine(stringer);
}
return stringToUpperArrays;
}
}
}
In CreateArray you define the array to size of numInArray + 1 but you fill the array only with numInArray strings, i.e. the last index is empty. When you try value.ToUpper(); on the empty index you get the exception.
In CreateArray change
stringArray = new string[(numInArray + 1)];
To
stringArray = new string[numInArray];
Or change
for (index = 0; index < numInArray; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
To
for (index = 0; index < stringArray.Length; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
You should erase the + 1 when you are initializing the array
stringArray = new string[(numInArray)];
in this method
private static string[] CreateArray(int numInArray)

How to parse below string in C#?

Please someone to help me to parse these sample string below? I'm having difficulty to split the data and also the data need to add carriage return at the end of every event
sample string:
L,030216,182748,00,FF,I,00,030216,182749,00,FF,I,00,030216,182750,00,FF,I,00
batch of events
expected output:
L,030216,182748,00,FF,I,00 - 1st Event
L,030216,182749,00,FF,I,00 - 2nd Event
L,030216,182750,00,FF,I,00 - 3rd Event
Seems like an easy problem. Something as easy as this should do it:
string line = "L,030216,182748,00,FF,I,00,030216,182749,00,FF,I,00,030216,182750,00,FF,I,00";
string[] array = line.Split(',');
StringBuilder sb = new StringBuilder();
for(int i=0; i<array.Length-1;i+=6)
{
sb.AppendLine(string.Format("{0},{1} - {2} event",array[0],string.Join(",",array.Skip(i+1).Take(6)), "number"));
}
output (sb.ToString()):
L,030216,182748,00,FF,I,00 - number event
L,030216,182749,00,FF,I,00 - number event
L,030216,182750,00,FF,I,00 - number event
All you have to do is work on the function that increments the ordinals (1st, 2nd, etc), but that's easy to get.
This should do the trick, given there are no more L's inside your string, and the comma place is always the sixth starting from the beginning of the batch number.
class Program
{
static void Main(string[] args)
{
String batchOfevents = "L,030216,182748,00,FF,I,00,030216,182749,00,FF,I,00,030216,182750,00,FF,I,00,030216,182751,00,FF,I,00,030216,182752,00,FF,I,00,030216,182753,00,FF,I,00";
// take out the "L," to start processing by finding the index of the correct comma to slice.
batchOfevents = batchOfevents.Substring(2);
String output = "";
int index = 0;
int counter = 0;
while (GetNthIndex(batchOfevents, ',', 6) != -1)
{
counter++;
if (counter == 1){
index = GetNthIndex(batchOfevents, ',', 6);
output += "L, " + batchOfevents.Substring(0, index) + " - 1st event\n";
batchOfevents = batchOfevents.Substring(index + 1);
} else if (counter == 2) {
index = GetNthIndex(batchOfevents, ',', 6);
output += "L, " + batchOfevents.Substring(0, index) + " - 2nd event\n";
batchOfevents = batchOfevents.Substring(index + 1);
}
else if (counter == 3)
{
index = GetNthIndex(batchOfevents, ',', 6);
output += "L, " + batchOfevents.Substring(0, index) + " - 3rd event\n";
batchOfevents = batchOfevents.Substring(index + 1);
} else {
index = GetNthIndex(batchOfevents, ',', 6);
output += "L, " + batchOfevents.Substring(0, index) + " - " + counter + "th event\n";
batchOfevents = batchOfevents.Substring(index + 1);
}
}
output += "L, " + batchOfevents + " - " + (counter+1) + "th event\n";
Console.WriteLine(output);
}
public static int GetNthIndex(string s, char t, int n)
{
int count = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == t)
{
count++;
if (count == n)
{
return i;
}
}
}
return -1;
}
}
Now the output will be in the format you asked for, and the original string has been decomposed.
NOTE: the getNthIndex method was taken from this old post.
If you want to split the string into multiple strings, you need a set of rules,
which are implementable. In your case i would start splitting the complete
string by the given comma , and than go though the elements in a loop.
All the strings in the loop will be appended in a StringBuilder. If your ruleset
say you need a new line, just add it via yourBuilder.Append('\r\n') or use AppendLine.
EDIT
Using this method, you can also easily add new chars like L or at the end rd Event
Look for the start index of 00,FF,I,00 in the entire string.
Extract a sub string starting at 0 and index plus 10 which is the length of the characters in 1.
Loop through it again each time with a new start index where you left of in 2.
Add a new line character each time.
Have a try the following:
string stream = "L,030216,182748,00,FF,I,00, 030216,182749,00,FF,I,00, 030216,182750,00,FF,I,00";
string[] lines = SplitLines(stream, "L", "I", ",");
Here the SplitLines function is implemented to detect variable-length events within the arbitrary-formatted stream:
string stream = "A;030216;182748 ;00;FF;AA;01; 030216;182749;AA;02";
string[] lines = SplitLines(batch, "A", "AA", ";");
Split-rules are:
- all elements of input stream are separated by separator(, for example).
- each event is bounded by the special markers(L and I for example)
- end marker is previous element of event-sequence
static string[] SplitLines(string stream, string startSeq, string endLine, string separator) {
string[] elements = stream.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries);
int pos = 0;
List<string> line = new List<string>();
List<string> lines = new List<string>();
State state = State.SeqStart;
while(pos < elements.Length) {
string current = elements[pos].Trim();
switch(state) {
case State.SeqStart:
if(current == startSeq)
state = State.LineStart;
continue;
case State.LineStart:
if(++pos < elements.Length) {
line.Add(startSeq);
state = State.Line;
}
continue;
case State.Line:
if(current == endLine)
state = State.LineEnd;
else
line.Add(current);
pos++;
continue;
case State.LineEnd:
line.Add(endLine);
line.Add(current);
lines.Add(string.Join(separator, line));
line.Clear();
state = State.LineStart;
continue;
}
}
return lines.ToArray();
}
enum State { SeqStart, LineStart, Line, LineEnd };
f you want to split the string into multiple strings, you need a set of rules, which are implementable. In your case i would start splitting the complete string by the given comma , and than go though the elements in a loop. All the strings in the loop will be appended in a StringBuilder. If your ruleset say you need a new line, just add it via yourBuilder.Append('\r\n') or use AppendLine.

Algorithm to find the three longest unique palindromes in a string

Using C#, write an algorithm to find the three longest unique palindromes in a string. For the three longest palindromes, report the palindrome text, start index and length in descending order of length. For example, the output for string,
sqrrqabccbatudefggfedvwhijkllkjihxymnnmzpop
should be:
Text: hijkllkjih, Index: 23, Length: 10 Text: defggfed, Index: 13, Length: 8 Text: abccba, Index: 5 Length: 6
Now I got to the part where I can write out the palindromes and its length but I have a problem with the index. Need help on how to include the index of the palindrome and how to get unique lengths
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string inputString = "sqrrqabccbatudefggfedvwhijkllkjihxymnnmzpop";
string currentStr = string.Empty;
List<string> listOfPalindromes = new List<string>();
char[] inputStrArr = inputString.ToCharArray();
for (int i = 0; i < inputStrArr.Length; i++)
{
for (int j = i+1; j < inputStrArr.Length; j++)
{
currentStr = inputString.Substring(i, j - i + 1);
if (IsPalindrome(currentStr))
{
listOfPalindromes.Add(currentStr);
}
}
}
var longest = (from str in listOfPalindromes
orderby str.Length descending
select str).Take(3);
foreach (var item in longest)
{
Console.WriteLine("Text: " + item.ToString() + " Index: " + + " Length: " + item.Length.ToString());
}
}
private static bool IsPalindrome(String str)
{
bool IsPalindrome = true;
if (str.Length > 0)
{
for (int i = 0; i < str.Length / 2; i++)
{
if (str.Substring(i, 1) != str.Substring(str.Length - (i + 1), 1))
{
IsPalindrome = false;
}
}
}
else
{
IsPalindrome = false;
}
return IsPalindrome;
}
}
}
ok now that's out of the way how do I get distinct lengths? can it be done by using DISTINCT or do I need to edit something else?
You need to store more information when a palindrome is found.
First define a class:
class PalindromeResult
{
public string Text { get; set; }
public int Index { get; set; }
}
Then instead of your List<string>, create a list of this class:
List<PalindromeResult> listOfPalindromes = new List<PalindromeResult>();
When a result is found, ad it like this
if (IsPalindrome(currentStr))
{
listOfPalindromes.Add(new PalindromeResult { Text = currentStr, Index = i});
}
You would have to update your sorting and printing accordingly.
The most optimal solution (as pointed out by Sinatr) would be to store the index of the palindromes as you find them.
You could instead use the IndexOf function to find the index of the first occurrence of a substring within a string.
For example inputString.IndexOf(item) could be used in your Console.WriteLine function.
Try This
public static bool IsPalindromic(int l)
{
IEnumerable<char> forwards = l.ToString().ToCharArray();
return forwards.SequenceEqual(forwards.Reverse());
}
public int LongestPalindrome(List<int> integers)
{
int length=0;
int num;
foreach (var integer in integers)
{
if (integer.ToString().Length > length)
{
num = integer;
length = integer.ToString().Length;
}
}
return num;
}
public void MyFunction(string input)
{
var numbers = Regex.Split(input, #"\D+").ToList();
var allPalindromes = (from value in numbers where !string.IsNullOrEmpty(value) select int.Parse(value) into i where IsPalindromic(i) select i).ToList();
if (allPalindromes.Count>0)
Console.WriteLine(LongestPalindrome(allPalindromes));
else
Console.WriteLine("Any Palindrome number was found");
}
you cans mix the 2 two functions to have a beautiful code but i done it like this to simplify.

Unable to split strings, and confusing ";" requirements

Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace DataAnalysis
{
class Data
{
public int InTime;
public string InLocation;
public bool Direction;
public int LOS_F;
// create a Data object from a CSV format string.
static Data FromString(string line)
{
var fields = line.split(",");
return new Data
{
InTime = TimeSpan.Parse(fields[3]),
InLocation = fields[5],
Direction = fields[5][0], // to get the direction E/N/S/W
LOS_F = float.Parse(fields[16])
};
}
}
class Program
{
string[] directions = new string[] { "E", "N", "S", "W" };
static void Main(string[] args)
{
var path = #"C:\Documents and Settings\Siva-Admin\Desktop\5.5 Capacity Models\";
// ^--- No need to escape the backslashes
var subdirs = Directory.GetDirectories(path);
// The subdirs variable contains the FULL paths
foreach (string subdir in subdirs)
{
List<List<float>> allAvgs = new List<List<float>>();
using (StreamWriter compiled = new StreamWriter(
Path.Combine(subdir, "compiledresults.csv")))
{
compiled.Write("heading,EastAvg,NorthAvg,SouthAvg,WestAvg");
for (int i = 1; i <= 10; i++)
{
List<Data> info = new List<Data>();
using (StreamReader reader = new StreamReader(
Path.Combine(subdir, "results" + i.ToString() + #"\JourneyTimes.csv")))
{
// Read the header line first!
string line = reader.ReadLine();
while ((line = reader.ReadLine()) != null)
info.Add(Data.FromString(line));
}
List<float> avgs = new List<float>();
for (string dir in directions)
{
List<Data> perDirection = info.Where(d => d.Direction = dir) as List<Data>;
float sum = perDirection.Sum(d => d.LOS_F);
float average = sum / perDirection.Count();
avgs.Add(average);
}
allAvgs.Add(avgs);
compiled.Write("results" + i.ToString() + "," + string.Join(",", avgs) + "\n");
}
compiled.Write("scenario_average");
for (int j = 1; j <= 4; j++)
{
compiled.Write("," + allAvgs.Sum(d => d[0]) / allAvgs.Count());
}
}
}
}
}
}
I get the following errors:
Error 1; expected(Line 67, "for (string dir in directions)" )
Error 2; expected(LINE 67, " " )
Error 3 'string' does not contain a definition for 'split' and no extension method 'split' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) (LINE 20, var fields = line.split (","); )
I do not understand the need for the ; as these are arguments being passed are they not? I also do not understand why I cannot split a string.
Error 1 and 2: Your for loop should be a foreach loop:
foreach (string dir in directions)
Error 3: the S in split should be upper case:
var fields = line.Split(',');
for (string dir in directions) should be foreach (string dir in directions)
EDIT to add:
Addtionally, here:
List<Data> perDirection = info.Where(d => d.Direction = dir) as List<Data>;
You seem to be making an assignment instead of a equality check, i.e
d.Direction = dir should be d.Direction == dir
However, it still won't work since you are comparing a string to a bool.
You need to replace line.split(",") with line.Split(',') (note the uppercase S).
(also replace for with foreach in line 67 as others have pointed out).
Error1 & Error2 use foreach instead of for;
Erorr3 it's Split instead of split.

Categories

Resources