I have my code to decrypt the string to numbers but i have the result
every time "-1-1-1"
protected void submit_Click(object sender, EventArgs e)
{
decryptScore(txtscore.Text);
}
public string decryptScore(string s)
{
string[] firstDigitArray = { "f85au", "kt50e", "cmt5s", "v5072", "fc5i3", "56f7l", "7gj81", "yn90y", "5o3ko", "ntakn" };
string[] secondDigitArray = { "hkym6", "xj97c", "54v6q", "nawf9", "9e1gp", "9gww9", "5oj5p", "0ba5t", "yizld", "bt064" };
string[] thirdDigitArray = { "uku91", "rn2k4", "uuq78", "nkurt", "8kxqs", "9p7kc", "hd8x6", "57b6o", "7iucu", "do6bq" };
string[] fourthDigitArray = { "0hdro", "0wqrc", "wa5ny", "857mg", "3f7ro", "kerph", "0mhw1", "tpb8f", "8rho3", "4hc11" };
string[][] digitsArray = {firstDigitArray, secondDigitArray, thirdDigitArray, fourthDigitArray};
string decryptedScore = "";
int scorelength = s.Length / 5;
for (int i = 0; i < scorelength; i++)
{
string d = s.Substring(i * 5, 5);
decryptedScore += (digitsArray[i][i].IndexOf(d));
}
score.Text = decryptedScore;
return decryptedScore;
}
public string decryptScore(string s)
{
var firstDigitArray = new List<string>{ "f85au", "kt50e", "cmt5s", "v5072", "fc5i3", "56f7l", "7gj81", "yn90y", "5o3ko", "ntakn" };
var secondDigitArray = new List<string> { "hkym6", "xj97c", "54v6q", "nawf9", "9e1gp", "9gww9", "5oj5p", "0ba5t", "yizld", "bt064" };
var thirdDigitArray = new List<string> { "uku91", "rn2k4", "uuq78", "nkurt", "8kxqs", "9p7kc", "hd8x6", "57b6o", "7iucu", "do6bq" };
var fourthDigitArray = new List<string> { "0hdro", "0wqrc", "wa5ny", "857mg", "3f7ro", "kerph", "0mhw1", "tpb8f", "8rho3", "4hc11" };
var digitsArray = new List<List<string>>{ firstDigitArray, secondDigitArray, thirdDigitArray, fourthDigitArray };
string decryptedScore = "";
int scorelength = s.Length / 5;
for (int i = 0; i < scorelength; i++)
{
string d = s.Substring(i * 5, 5);
decryptedScore += (digitsArray[i].FindIndex(x=>x==d));
}
return decryptedScore;
}
PS: Don't forget if scorelength is greater or equal to 4 you'll get an exception(since you only have 4 digitArrays)
In the line
decryptedScore += (digitsArray[i][i].IndexOf(d));
you are searching for a string a single string for a the value. You need to search the array.
Change this line to
decryptedScore += Array.IndexOf(digitsArray[i], d);
This will search the array for a particular value and return you it's index. As a result you will get the required number back.
Replace
decryptedScore += (digitsArray[i][i].IndexOf(d));
with
decryptedScore += Array.IndexOf(digitsArray[i], d);
Related
I have this class:
public class Student
{
private int[] note;//vector de note
private DateTime dataInrolarii;
private int nrRestante;
private readonly int nrMatricol;
private const string sex = "feminin"
public static int anStudiu = 3;
public Student(string cnp, string nume, int nrMatricol, DateTime dataInrolarii, int nrRestante, int[] note) : base(cnp, nume)
{
this.nrMatricol = nrMatricol;
this.dataInrolarii = Convert.ToDateTime(dataInrolarii);
this.nrRestante = nrRestante;
this.note = new int[note.Length];
for (int i = 0; i < note.Length; i++)
this.note[i] = note[i];
}
}
Of course, i have getters, setters, toString() overloaded and more.
I have a text file with this object :
2920118080023, George, 2, 12/09/2016, 4, 10 3 4
and I want to read from file and displat in a textBox the Students from file. but i don't really know how to do this with the vector note.
Here is that i wrote:
private void button_CitireTXT_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("citiretxt.txt");
string linie = null;
while ((linie = sr.ReadLine()) != null)
{
try
{//oricare ar fi tipul unui atribut citit din fisier, ele sunt STRING acolo
string cnp = linie.Trim().Split(',')[0];
string nume = linie.Trim().Split(',')[1];
int nrmat = Convert.ToInt32(linie.Trim().Split(',')[2]);
string datainrolString = linie.Trim().Split(',')[3];
DateTime datainrol = DateTime.Parse(datainrolString);
int nrRest = Convert.ToInt32(linie.Trim().Split(',')[4]);
string noteString = linie.Split(' ')[5];
for(int i=0;i< noteString.Length;i++)
{
noteString[i] = Convert.ToInt32(noteString[i]);
string[] notesString
}
Student s = new Student(cnp, nume, nrmat, datainrol, nrRest, note);
tb_CitireDinTxt.Text += s.ToString() + Environment.NewLine;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
How to read the vector NOTE from file? Thank you
UPDATE:
private void button_CitireTXT_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("citiretxt.txt");
string linie = null;
while ((linie = sr.ReadLine()) != null)
{
try
{
string cnp = linie.Trim().Split(',')[0];
string nume = linie.Trim().Split(',')[1];
int nrmat = Int32.Parse(linie.Trim().Split(',')[2]);
string datainrolString = linie.Trim().Split(',')[3];
DateTime datainrol = DateTime.Parse(datainrolString);
int nrRest = Int32.Parse(linie.Trim().Split(',')[4]);
int[] notes = Array.ConvertAll(linie.Split(',')[5].Split(' '), int.Parse);
Student s1 = new Student(cnp, nume, nrmat, datainrol, nrRest, notes);
tb_CitireDinTxt.Text += s1.ToString() + Environment.NewLine;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Writing answer by considering, Vector(from C++) -> List(in C#).
If following is your file content,
2920118080023, George, 2, 12/09/2016, 4, 10 3 4
Split by ,. Then your string at 5th index will contain 10 3 4. Now to convert it into array of integer use Array.ConvertAll() or you can convert it to List as well
Try bellowed code
//Converting into int array
int[] notes = Array.ConvertAll(linie.Split(',')[5].Split(' '), int.Parse)
//Converting into List<int>
List<int> notes= Array.ConvertAll(linie.Split(',')[5].Split(' '), int.Parse).ToList()
Instead of
string noteString = linie.Split(' ')[5];
for(int i=0;i< noteString.Length;i++)
{
noteString[i] = Convert.ToInt32(noteString[i]);
string[] notesString
}
I can't permanently replace the array members. When I change the value of String Clue, the string being displayed only displays the current value of clue. I think the problem us on the initialization of char[]. I tried to put them in other parts of the code but it produces error. Beginner here! Hope you can help me. Thanks! :)
private void clues(String clue)
{
int idx = numb[wordOn]+4;
char[] GuessHide = Words[idx].ToUpper().ToCharArray();
char[] GuessShow = Words[idx].ToUpper().ToCharArray();
for (int a = 0; a < GuessHide.Length; a++)
{
if (GuessShow[a] != Convert.ToChar(clue.ToUpper()))
GuessHide[a] = '*';
else
GuessHide[a] = Convert.ToChar(clue.ToUpper());
}
Guess(string.Join("", GuessHide));
}
Edited - because you initalize GuessHide at each call of calls in your code and you do not store its current state you basically reset it each time. Still, you can make some small changes in your code like this:
private static void clues(string clue, char[] GuessHide, char[] GuessShow)
{
for (int a = 0; a < GuessHide.Length; a++)
{
if (GuessShow[a] == Convert.ToChar(clue.ToUpper()))
{
GuessHide[a] = Convert.ToChar(clue.ToUpper());
}
}
Console.WriteLine(string.Join("", GuessHide));
}
Call it like this:
clues("p", GuessHide, GuessShow);
clues("a", GuessHide, GuessShow);
Initialise GuessShow and GuessHide in the outside code like this:
char[] GuessHide = new string('*', Words[idx].Length).ToCharArray();
char[] GuessShow = Words[idx].ToUpper().ToCharArray();
public class Program
{
static string[] Words;
static string[] HiddenWords;
public static void Main()
{
Words = new string[] { "Apple", "Banana" };
HiddenWords = new string[Words.Length];
for (int i = 0; i < Words.Length; i++)
{
HiddenWords[i] = new string('*', Words[i].Length);
}
Guess('P', 0);
Guess('a', 0);
Guess('A', 1);
Guess('N', 1);
Console.ReadLine();
}
private static void Guess(char clue, int idx)
{
string originalWord = Words[idx];
string upperedWord = Words[idx].ToUpper();
char[] foundSoFar = HiddenWords[idx].ToCharArray();
clue = char.ToUpper(clue);
for (int i = 0; i < upperedWord.Length; i++)
{
if (upperedWord[i] == clue)
{
foundSoFar[i] = originalWord[i];
}
}
HiddenWords[idx] = new string(foundSoFar);
Console.WriteLine(HiddenWords[idx]);
}
}
My function is supposed to split a string by "&" ";" and "," and return a triple jagged array and vice versa. (From data like: 1,2,3;4,5,6&1,2,3;4,5,6)
I've been struggling hard to make it work, now for some reason I'm getting a system.argumentnullexception on
Array.Copy(playerOneEnts, allEnts[0], playerOneEnts.Length);
Array.Copy(playerTwoEnts, allEnts[1], playerTwoEnts.Length);
Full code:
public string convertToString(string[][][] allEnts)
{
string Player = string.Empty;
string[][] playerOneEnts = new string[maxEnts][];
string[][] playerTwoEnts = new string[maxEnts][];
Array.Copy(allEnts[0], playerOneEnts, allEnts[0].Length);
Array.Copy(allEnts[1], playerTwoEnts, allEnts[1].Length);
for (int j = 0; j < playerOneEnts.Length; j++)
{
for (int i = 0; i < playerOneEnts[j].Length; i++)
{
Player += playerOneEnts[j][i] + ",";
}
Player = Player.TrimEnd(',');
Player += ";";
}
Player = Player.TrimEnd(';');
Player += "&";
for (int j = 0; j < playerTwoEnts.Length; j++)
{
for (int i = 0; i < playerTwoEnts[j].Length; i++)
{
Player += playerTwoEnts[j][i] + ",";
}
Player = Player.TrimEnd(',');
Player += ";";
}
Player = Player.TrimEnd(';');
return Player;
}
public string[][][] convertToArray(string ents)
{
string[] p = new string[2];
string[][] playerOneEnts = new string[maxEnts][];
string[][] playerTwoEnts = new string[maxEnts][];
string[][][] allEnts = new string[2][][];
p = ents.Split('&');
try
{
playerOneEnts = p[0].Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(chunk => chunk.Split(',')).ToArray();
playerTwoEnts = p[1].Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(chunk => chunk.Split(',')).ToArray();
MessageBox.Show(playerOneEnts.Length.ToString());
Array.Copy(playerOneEnts, allEnts[0], playerOneEnts.Length);
Array.Copy(playerTwoEnts, allEnts[1], playerTwoEnts.Length);
}
catch
{
MessageBox.Show("unable to convert string", "Fatal Error");
}
return allEnts;
}
The code looks like a disaster to me, if anyone knows a nicer way to convert this to a string I'd be happy for any ideas. Getting rid of my Error would help me enough already.
Thanks!
Here is example using Linq (requires .Net 4.0):
var source = "1,2,3;4,5,6&1,2,3;4,5,6";
string[][][] decoded = source.Split('&').Select(x => x.Split(';').Select(y => y.Split(',').ToArray()).ToArray()).ToArray();
string reencoded = String.Join("&", decoded.Select(x => String.Join(";", x.Select(y => String.Join(",", y)))));
Alternatively IEnumarable generics can be used to avoid conversion to arrays.
Warning: This code doesn't validates input e.g. array lengths.
Edit: Re-encoder for .NET 3.5:
var reencoded = String.Join("&", decoded.Select(x => String.Join(";", x.Select(y => String.Join(",", y)).ToArray())).ToArray());
You can do it using nested for-loops like this:
string p = "1,2,3;4,5,6&1,5,3;4,5,9";
List<List<List<string>>> result = new List<List<List<string>>>();
foreach (var a in p.Split('&'))
{
List<List<string>> level2 = new List<List<string>>();
foreach (var b in a.Split(';'))
{
level2.Add(new List<string>(b.Split(',')));
}
result.Add(level2);
}
var x = result[0][1][2]; // This will result in '6'.
The encoding is similar:
string encoded;
List<string> dec1 = new List<string>();
foreach (var a in result)
{
string e = "";
List<string> z = new List<string>();
foreach (var b in a)
{
z.Add(String.Join(",", b));
}
e = String.Join(";", z);
dec1.Add(e);
}
encoded = String.Join("&", dec1);
Heres a fun problem I have.
I have a function that returns a var of items;
var Items = new { sumList = SumList, ratesList = List, sum = List.Sum() };
return Items;
From a function that is dynamic:
public override dynamic GetRates()
and I return it to a function I else where and try to apply it to my code:
dynamic res = cl.mainC.GetRates();
List<double> MashkantaSumList = res.sumList;
Now when I try to apply it, it says the object doesnt exist. But if I look in the debugger the items are happily there as a generic list or what not.
How do I resolve this?
EDIT:
as per request I'll post the full code:
//virtual
public virtual dynamic TotalMashkanta(int i, double sum, double ribit, string[] discount)
{
return 0;
}
//override
public override dynamic TotalMashkanta(int i, double sum, double ribit, string[] discount)
{
double SumTemp = sum;
double monthlyRibit = ribit / 12;
Double permPayPerMont = Financial.Pmt(monthlyRibit, i, sum, 0, DueDate.EndOfPeriod);
List<double> MashkantaList = new List<double>();
List<double> MashkantaSumList = new List<double>();
for (int j = 1; j <= i; j++)
{
MashkantaList.Add(Mashkanta(j, sum, ribit, permPayPerMont) * (1 - CalcDiscount((j / 12) + 1, discount)));
SumTemp = getSum(j, sum, ribit, permPayPerMont * -1); ;
MashkantaSumList.Add(SumTemp);
}
var K_Mashkanta = new { sumList = MashkantaSumList, ratesList = MashkantaList, sum = MashkantaList.Sum() };
return K_Mashkanta;
}
//Function that calls the results
public void GetSilukinTable(string Path, string ClientID, DAL.Client client, string partner_checked, string insurance_Amount, string Premiya_Structure_Mashkanta, string Premiya_Life_Mashkanta, string Discount_Life_Mashkanta, string Loan_Period,string Loan_EndDate, string Bank, string Loan_Interest, string Loan_Amount, string Discount_Loan, string AgentNotes, string ManID)
{
BL.CalculateLogic.Companies t = BL.CalculateLogic.Companies.כלל;
if(ManID == "211") t = BL.CalculateLogic.Companies.הפניקס;
if(ManID == "207") t = BL.CalculateLogic.Companies.הראל;
if(ManID == "206") t = BL.CalculateLogic.Companies.מנורה;
if(ManID == "208") t = BL.CalculateLogic.Companies.הכשרה;
BL.CalculateLogic cl = new BL.CalculateLogic(client, t);
DateTime LoanEnd = DateTime.Now;
int months = 0;
if (DateTime.TryParse(Loan_EndDate, out LoanEnd))
months = BL.Calculating_Companies.Company.GetMonthsBetween(DateTime.Now, LoanEnd);
else
months = Int32.Parse(Loan_Period) * 12;
string[] Discount = Discount_Loan.Split('-');
dynamic res = cl.mainC.TotalMashkanta(months, Double.Parse(Loan_Amount), Double.Parse(Loan_Interest.Trim('%')), Discount);
var MashkantaSumList = res.sumList;
List<double> MashkantaList = res.ratesList;
List<double> MashkantaSumListPartner = new List<double>();
List<double> MashkantaListPartner = new List<double>();
List<double> MashkantaListSum = res.ratesList;
}
The compiler is happy about it because dynamic is compiled and checked at run time. Whatever the problem is, the types don't match. It evaluates this at run time, so you won't see issues at compile time. (Advice: use dynamic only when you really must! Else you will have this kind of problems all the time!)
I tried your code using this and it works fine:
static dynamic GetRates()
{
List<double> SumList = new List<double>();
List<double> List = new List<double>();
var Items = new { sumList = SumList, ratesList = List, sum = List.Sum() };
return Items;
}
static void Main(string[] args)
{
dynamic res = GetRates();
List<double> MashkantaSumList = res.sumList;
}
Dear stackoverflow members,
I have this string:
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
I want to search for the values where the "keyword" is Position. In this case I want to get back 1 and 2. Each value is "indexed" with its own "keyword". So the value 1 in this string has the Position seperator. The value 1234 has the Article seperator and the value 4321 has the Quantity seperator.
I need a way to search through the string and want to get all positions, articles and quantitys back. Without the keywords.
Output shout be:
string[] position = {"1", "2"};
string[] article = {"1234", "4323"};
string[] quantity = {"4321", "3323"};
Hopefully some can help me here.
Thanks!
This is q quick solution I've come up with in LinqPad:
void Main()
{
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
var Articles = Indices(data, "Article").Dump("Articles: ");
var Posistions = Indices(data, "Position").Dump("Positions :");
var Quantities = Indices(data, "Quantity").Dump("Quantities :");
}
// Define other methods and classes here
public List<int> Indices(string source, string keyword)
{
var results = new List<int>();
//source: http://stackoverflow.com/questions/3720012/regular-expression-to-split-string-and-number
var temp = Regex.Split(source, "(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)").ToList().Where (r => !String.IsNullOrEmpty(r)).ToList();
//select the list with index only where key word matches
var indices = temp.Select ((v,i) => new {index = i, value = v})
.Where (t => t.value == keyword);
foreach (var element in indices)
{
int val;
//get previous list entry based on index and parse it
if(Int32.TryParse(temp[element.index -1], out val))
{
results.Add(val);
}
}
return results;
}
Output:
Here's a possible algorithm:
Run trough the list and take each number / keyword.
Put them in a dictionary with key "keyword", value a list with all "numbers".
Iterate the dictionary and print they key + its values.
Below snippet can use to get the output like what you expected.
string data = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
StringBuilder sb = new StringBuilder();
StringBuilder sbWord = new StringBuilder();
bool isDigit = false;
bool isChar = false;
Dictionary<int, string> dic = new Dictionary<int, string>();
int index = 0;
for (int i = 0; i < data.Length; i++)
{
if (char.IsNumber(data[i]))
{
isDigit = true;
if (isChar)
{
dic.Add(index, sb.ToString() + "|" + sbWord.ToString());
index++;
isChar = false;
sb.Remove(0, sb.Length);
sbWord.Remove(0, sbWord.Length);
}
}
else
{
isDigit = false;
isChar = true;
sbWord.Append(data[i]);
}
if (isDigit)
sb.Append(data[i]);
if (i == data.Length - 1)
{
dic.Add(index, sb.ToString() + "|" + sbWord.ToString());
}
}
List<string> Position = new List<string>();
List<string> Article = new List<string>();
List<string> Quantity = new List<string>();
if (dic.Count > 0)
{
for (int i = 0; i < dic.Count; i++)
{
if (dic[i].Split('|')[1] == "Position")
Position.Add(dic[i].Split('|')[0]);
else if (dic[i].Split('|')[1] == "Article")
Article.Add(dic[i].Split('|')[0]);
else
Quantity.Add(dic[i].Split('|')[0]);
}
}
string[] Position_array = Position.ToArray();
string[] Article_array = Article.ToArray();
string[] Quantity_array = Quantity.ToArray();
Try this simple solution.
class StrSplit{
public static void main(String args[]){
int i;
String str = "1Position1234Article4321Quantity2Position4323Article3323Quantity";
String pattern= "(?<=Position)|(?<=Article)|(?<=Quantity)";
String[] parts = str.split(pattern);
List<String> Position = new ArrayList<String>();
List<String> Article = new ArrayList<String>();
List<String> Quantity = new ArrayList<String>();
for( i=0;i<parts.length;i++)
{
pattern="Position";
String[] subParts;
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Position.add(subParts[0]);
}
pattern="Article";
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Article.add(subParts[0]);
}
pattern="Quantity";
if(parts[i].contains(pattern))
{
subParts = parts[i].split(pattern);
Quantity.add(subParts[0]);
}
}
System.out.println("Position:");
for(i = 0; i < Position.size(); i++) {
System.out.println(Position.get(i));
}
System.out.println("Article:");
for(i = 0; i < Article.size(); i++) {
System.out.println(Article.get(i));
}
System.out.println("Quantity:");
for(i = 0; i < Quantity.size(); i++) {
System.out.println(Quantity.get(i));
}
}
}
Output:
Position:
1
2
Article:
1234
4323
Quantity:
4321
3323