I need to create dynamic references to both strings and string Arrays within a for loop.
Is the following correct? In particular where I am trying to create a dynamic string reference string sRef = "svert"+num; and later a dynamic Array reference string arrayRef = "s_array"+num;
Any feedback welcome.
Vector3[] meshVerts = foo;
for(int num=0; num < meshVerts.Length;num++){
string sRef = "svert"+num;
sRef =meshVerts[num].ToString( format: "F4");
sRef= sRef.Substring(1, 3);
string arrayRef = "s_array"+num;
string[] arrayRef = sRef.Split(',');
}
'''
I have prepared a sample and test code for your question. I hope you find it interesting.
//fill vector3 array
Vector3[] meshVerts = new Vector3[3];
for (int i = 0; i < meshVerts.Length; i++)
{
meshVerts[i] = new Vector3(i, i + 1, i + 2);
}
//fill string array
string[] arrayRef = new string[meshVerts.Length];
for (int num = 0; num < meshVerts.Length; num++)
{
arrayRef[num] = string.Format("s_array{0}: {1}", num, meshVerts[num]);
}
//show vector3 array and string array
for (int i = 0; i < meshVerts.Length; i++)
{
Console.WriteLine(string.Format("Vector3 Array Row{0}: X={1} ,Y={2} ,Z={3}", i, meshVerts[i].X, meshVerts[i].Y, meshVerts[i].Z));
string[] newArray = arrayRef[i].Split(',');
string firstCell = newArray[0].Split(':')[1].Replace("<", "");
Console.WriteLine(string.Format("{0} Row{1}: X={2} ,Y={3} ,Z={4}", newArray[0].Split(':')[0], i, firstCell, newArray[1], newArray[2].Replace(">", "")));
}
Related
Basically, I am trying to split an array and want to pass its value into another array.
But, I am not able to do it.It is givin an error:
Cannot implicitly convert type String[] to string"
StreamReader EmployeeFile = new StreamReader(#"C:\Users\user\Desktop\FoodDeliverySystem\Employee_details.txt");
String ReadEmployeeData = EmployeeFile.ReadToEnd();
String[] ReadEmployeeDataByLine = ReadEmployeeData.Split(';');
for (int k = 0; k < 5; k++)
{
for (int l = 0; l < 5; l++)
{
Console.WriteLine("test");
String[,] ReadEmployeeDataByLineByCategorie = new string[k, l];
ReadEmployeeDataByLineByCategorie[k,l] = ReadEmployeeDataByLine[l].Split(',');
}
}
Since you can't be sure of how many of those values you're gonna have in each category of yours, you should use jagged arrays
That should do:
var readEmployeeDataByLine = new StreamReader(#"C:\pathToFile.txt").ReadToEnd().Split(';');
var readEmployeeDataByLineByCategorie = new string[readEmployeeDataByLine.Length][];
for (int i = 0; i < readEmployeeDataByLineByCategorie.Length; i++)
readEmployeeDataByLineByCategorie[i] = readEmployeeDataByLine[i].Split(',');
ReadEmployeeDataByLineByCategorie[k,l] is a string
while ReadEmployeeDataByLine[l].Split(',') is a string[]
string[] ReadEmployeeDataByLine = ReadEmployeeData.Split(';');
for(int i = 0;i< ReadEmployeeDataByLine.Length;i++)
{
string split = ReadEmployeeDataByLine[l].Split(',');
for(int j=0; j<split.Length;j++)
ReadEmployeeDataByLineByCategorie[i,j] = split[j]
}
public float[] HitungFitness()
{
float[] fitness = new float[populasi];
for (var individu = 0; individu < populasi; individu++)
{
fitness[individu] = CekConstraint(individu);
}
string[] sort = new string[populasi];
for (int i = 0; i < populasi; i++)
{
sort[i] = string.Format("\nIndividu {0} :Fitness {1}",(i + 1), fitness[i]);
}
bool swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < populasi-1 ; i++)
{
string[] strI = sort[i].Split('.');
float fitI = float.Parse(string.Format("0.{0}", strI[1]));
string[] strJ = sort[i + 1].Split('.');
float fitJ = float.Parse(string.Format("0.{0}", strJ[1]));
if (fitI < fitJ)
{
string sTmp = sort[i];
sort[i] = sort[i + 1];
sort[i + 1] = sTmp;
swapped = true;
}
}
}
return fitness;
}
variable populasi assign = 12
A function CekConstraint is giving a return value between '0.***' to '1'
I have a problem with:
float fitI = float.Parse(string.Format("0.{0}", strI[1]));
or
float fitJ = float.Parse(string.Format("0.{0}", strI[1]));
When the strI or strJ just giving one value of array like strJ[1] or stri[1] then I'm getting the Index was outside bounds of the array. I recognize the error but how do I fix this?
Please help me.
string[] strI = sort[i].Split('.');
float fitI = float.Parse(string.Format("0.{0}", strI[1]));
sort[i] string doesn't have . in it. Because of that when you call Split('.') you produce only array with 1 item. Because of that on strI[1] you receive and exception, there is no second elements in strI array.
Error is because it is not getting value in strI[1] or strJ[1]. It may have happened because of a "." is not found in sort[i]. Hence we can see put a condition based on strI and strJ array Length.
Change your inner for loop as
for (int i = 0; i < populasi-1 ; i++)
{
float fitI = 0.0;
float fitJ = 0.0;
string[] strI = sort[i].Split('.');
if(strI.Length > 1)
fitI = float.Parse(string.Format("0.{0}", strI[1]));
string[] strJ = sort[i + 1].Split('.');
if(strJ.Length > 1)
fitJ = float.Parse(string.Format("0.{0}", strJ[1]));
if (fitI < fitJ)
{
string sTmp = sort[i];
sort[i] = sort[i + 1];
sort[i + 1] = sTmp;
swapped = true;
}
}
Why so many loops, use a list or dictinary in place or array and use foreach loop to avoid the out-of-range exception.
float[] fitness = new float[populasi];
//create a list for this
string[] sort = new string[populasi];
//another list
and do foreach looping
I'm making a webshop for school and had a quick question.
I'm trying to write a code that generates a random coupon code and it actually works (did some extreme programming in Console Application), but it's simply not efficient.
static void Main(string[] args)
{
Random r = new Random();
string ALphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int size = 4;
char[] code1 = new char[size]
char[] code2 = new char[size]
char[] code3 = new char[size]
for (int i = 0; i < size; i++)
{
code1[i] = Alphabet[r.Next(Alphabet.Length)];
code2[i] = Alphabet[r.Next(Alphabet.Length)];
code3[i] = Alphabet[r.Next(Alphabet.Length)];
}
string code4 = new string(code1);
string code5 = new string(code2);
string code6 = new string(code3);
Console.WriteLine(code4 + " - " + code5 + " - " + code6);
Console.ReadLine();
}
This works.. somehow. But I would like to see it more efficient, because when I want to generate 100 coupons... this isn't really the way to do that.
I did see something on joining strings, use string.Insert to get that " - " in between and loop it multiple times, but I couldn't get a clear tutorial on how to do that with... well this kind of code.
Anyone got a efficient and (preferable) easy solution?
=======
UPDATE!
this does end up in a database eventually
You could be using a StringBuilder for this:
StringBuilder sb = new StringBuilder();
Random r = new Random();
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int size = 16;
for (var i = 0; i < size; i++)
{
sb.Append(Alphabet[r.Next(Alphabet.Length)]);
}
Console.WriteLine(sb.ToString());
If you want less code you can make use of a GUID and format it.
Guid.NewGuid().ToString("N").Substring(0, 16);
Update, just saw you needed some formatting between each part of the coupon, so I changed it a litle bit:
StringBuilder sb = new StringBuilder();
Random r = new Random();
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int pieces = 3, pieceSize = 4;
for (var i = 0; i < pieces; i++)
{
if(i != 0)
sb.Append(" - ");
for (var j = 0; j < pieceSize; j++)
{
sb.Append(Alphabet[r.Next(Alphabet.Length)]);
}
}
Console.WriteLine(sb.ToString());
Code is not quite good, but for school app will play I guess )
static string GenerateCoupon(Random r)
{
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int size = 4;
char[] code1 = new char[size];
char[] code2 = new char[size];
char[] code3 = new char[size];
for (int i = 0; i < size; i++)
{
code1[i] = Alphabet[r.Next(Alphabet.Length)];
code2[i] = Alphabet[r.Next(Alphabet.Length)];
code3[i] = Alphabet[r.Next(Alphabet.Length)];
}
string code4 = new string(code1);
string code5 = new string(code2);
string code6 = new string(code3);
return string.Format("{0}-{1}-{2}", code4, code5, code6);
}
static void Main(string[] args)
{
Random rnd = new Random();
for (int i = 0; i < 100;i++ )
Console.WriteLine(GenerateCoupon(rnd));
Console.ReadLine();
}
I have a DataTable that I get from the DB, I want to create a 2d array in the code behind (once I get the DataTable..), and then pass it as a 2d array to Javascript.
this is what I tried to code :
int[,] videoQarray = new int[dt_questionVideo.Rows.Count,dt_questionVideo.Columns.Count ];
string[,] videoQarrayTitle = new string[dt_questionVideo.Rows.Count, dt_questionVideo.Columns.Count ];
for (var i = 0; i < dt_questionVideo.Rows.Count ; i++)
{
for (int j = 0; j < dt_questionVideo.Columns.Count; j++)
{
videoQarray[i,j] = Convert.ToInt32(dt_questionVideo.Rows[i][0]);
videoQarrayTitle[i,j] = dt_questionVideo.Rows[i][1].ToString();
}
}
string createArrayScript = string.Format("var videQarray = [{0}];", string.Join(",", videoQarray));
createArrayScript += string.Format("var videQarrayList = [{0}];", string.Join(",", videoQarrayTitle));
Page.ClientScript.RegisterStartupScript(this.GetType(), "registerVideoQArray", createArrayScript, true);
well, in the browser console it says that videoQarray is not defined..
I wonder how can I do that properly..
Probably the variable is being defined inside a function and therefore is hidden for other parts of code. Try "window.videoQArray" insted of "var ":
string createArrayScript = string.Format("window.videQarray = [{0}];", string.Join(",", videoQarray));
createArrayScript += string.Format("window.videQarrayList = [{0}];", string.Join(",", videoQarrayTitle));
Edit: It's a 2d array (ok, you wrote that very clearly in the question but I didn't see). Use JavaScriptSerializer:
var serializer = new JavaScriptSerializer();
string createArrayScript = string.Format("window.videQarray = {0};", serializer.Serialize(videoQarray));
createArrayScript += string.Format("window.videQarrayList = {0};", serializer.Serialize(videoQarrayTitle));
Use The following function:
public static string ArrayToString2D(string[,] arr)
{
StringBuilder str = new StringBuilder();
str.Append("[['");
for (int k = 0; k < arr.GetLength(0); k++)
{
for (int l = 0; l < arr.GetLength(1); l++)
{
if (arr[k, l] == null)
str.Append("','");
else
str.Append(arr[k, l].ToString() + "','");
}
str.Remove(str.Length - 2, 2);
str.Append("],['");
}
str.Remove(str.Length - 4, 4);
str.Append("]]");
return str.ToString();
}
in the code behind have the following properties:
private string[,] upperLabels ;
public string UpperLabel
{
get
{ return Utils.ArrayToString2D(upperLabels); }
}
in the javascript use the following :
var upperSplitted = <%=UpperLabel%> ;
var value = upperSplitted[0][0];
I need a C# function that takes 2 strings as an input and return an array of all possible combinations of strings.
private string[] FunctionName(string string1, string string2)
{
//code
}
The strings input will be in the following format:
string1: basement
string2: a*fa
Now what I need is all combinations of possible strings using the characters in String2 (ignoring the * symbols), and keeping them in the same character position like this:
baaement, baaefent, baaefena, basefent, basemena, etc.
EDIT:
This is not homework. I need this function for a piece of a program I am doing.
The following is the code I have so far but it has some bugs.
static List<string> combinations = new List<string>();
static void Main(string[] args)
{
//include trimming of input string
string FoundRes = "incoming";
string AltRes = "*2*45*78";
List<int> loc = new List<int>();
string word = "";
for (int i = 0; i < AltRes.Length; i++)
{
if (AltRes[i] != '*')
{
loc.Add(i);
word += AltRes[i];
}
}
generate(word);
string[] aaa = InsertSymbol(FoundRes, loc.ToArray(), AltRes, combinations);
Console.WriteLine("input string: " + FoundRes);
Console.WriteLine("Substitute string: " + AltRes);
Console.WriteLine("============Output============");
for (int j = 0; j < aaa.Length; j++)
{
Console.WriteLine(aaa[j]);
}
Console.ReadKey();
}//
private static void generate(string word)
{
// Add this word to combination results set
if (!combinations.Contains(word))
combinations.Add(word);
// If the word has only one character, break the recursion
if (word.Length == 1)
{
if (!combinations.Contains(word))
combinations.Add(word);
return;
}
// Go through every position of the word
for (int i = 0; i < word.Length; i++)
{
// Remove the character at the current position
// call this method with the String
generate(word.Substring(0, i) + word.Substring(i + 1));
}
}//
private static string[] InsertSymbol(string orig, int[] loc, string alternative, List<string> Chars)
{
List<string> CombinationsList = new List<string>();
string temp = "";
for (int i = 0; i < Chars.Count; i++)
{
temp = orig;
for (int j = 0; j < Chars[i].Length; j++)
{
string token = Chars[i];
if (alternative.IndexOf(token[j]) == loc[j])
{
temp = temp.Remove(loc[j], 1);
temp = temp.Insert(loc[j], token[j].ToString());
// int pos = sourceSubst.IndexOf(token[j]);
// sourceSubst = sourceSubst.Remove(pos, 1);
// sourceSubst = sourceSubst.Insert(pos, ".");
}
else
{
temp = temp.Remove(alternative.IndexOf(token[j]), 1);
temp = temp.Insert(alternative.IndexOf(token[j]), token[j].ToString());
}
}
CombinationsList.Add(temp);
}
return CombinationsList.ToArray();
}//
It does sound like homework. As a suggestion, I would ignore the first parameter and focus on getting all possible permutations of the second string. What's turned off, what's turned on, etc. From that list, you can easily come up with a method of swapping out characters of the first string.
On that note, I'm in the uncomfortable position of having a function ready to go but not wanting to post it because of the homework implication. I'd sure love for somebody to review it, though! And technically, there's two functions involved because I just happened to already have a generic function to generate subsets lying around.
Edit: OP says it isn't homework, so here is what I came up with. It has been refactored a bit since the claim of two functions, and I'm more than open to criticism.
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main()
{
string original = "phenomenal";
string pattern = "*xo**q*t**";
string[] replacements = StringUtility.GetReplacementStrings(original, pattern, true);
foreach (string replacement in replacements)
Console.WriteLine(replacement);
Console.Read();
}
public static class StringUtility
{
public static string[] GetReplacementStrings(string original, string pattern, bool includeOriginal)
{
// pattern and original might not be same length
int maxIndex = Math.Max(original.Length, pattern.Length);
List<int> positions = GetPatternPositions(pattern, maxIndex, '*');
List<int[]> subsets = ArrayUtility.CreateSubsets(positions.ToArray());
List<string> replacements = GenerateReplacements(original, pattern, subsets);
if (includeOriginal)
replacements.Insert(0, original);
return replacements.ToArray();
}
private static List<string> GenerateReplacements(string original, string pattern, List<int[]> subsets)
{
List<string> replacements = new List<string>();
char[] temp = new char[original.Length];
foreach (int[] subset in subsets)
{
original.CopyTo(0, temp, 0, original.Length);
foreach (int index in subset)
{
temp[index] = pattern[index];
}
replacements.Add(new string(temp));
}
return replacements;
}
private static List<int> GetPatternPositions(string pattern, int maxIndex, char excludeCharacter)
{
List<int> positions = new List<int>();
for (int i = 0; i < maxIndex; i++)
{
if (pattern[i] != excludeCharacter)
positions.Add(i);
}
return positions;
}
}
public static class ArrayUtility
{
public static List<T[]> CreateSubsets<T>(T[] originalArray)
{
List<T[]> subsets = new List<T[]>();
for (int i = 0; i < originalArray.Length; i++)
{
int subsetCount = subsets.Count;
subsets.Add(new T[] { originalArray[i] });
for (int j = 0; j < subsetCount; j++)
{
T[] newSubset = new T[subsets[j].Length + 1];
subsets[j].CopyTo(newSubset, 0);
newSubset[newSubset.Length - 1] = originalArray[i];
subsets.Add(newSubset);
}
}
return subsets;
}
}
}
since it's hopw work I'd only suggest some way to solve the problem rather than writing the code.
if you loop the second parameter every time you hit a letter you'll have to options either use the letter from the first argument or the letter from the second. collect all these optins together with the index. keep a list of the parts from the first argument that will never change. iterate thorugh those two lists to created all the possible permutations
Decimal to Binary converted code is stolon copied from here.
static void Main()
{
string string1 = "basement";
string string2 = "**a*f**a";
string[] result = GetCombinations(string1, string2);
foreach (var item in result)
{
Console.WriteLine(item);
}
}
private static string[] GetCombinations(string string1, string string2)
{
var list = new List<List<char>> { new List<char>(), new List<char>() };
var cl = new List<char>();
List<string> result = new List<string>();
for (int i = 0; i < string1.Length; i++)
{
if (string2[i] == '*')
{
cl.Add(string1[i]);
}
else
{
list[0].Add(string1[i]);
list[1].Add(string2[i]);
}
}
int l = list[0].Count;
for (int i = 0; i < (Int64)Math.Pow(2.0,l); i++)
{
string s = ToBinary(i, l);
string ss = "";
int x = 0;
int y = 0;
for (int I = 0; I < string1.Length; I++)
{
if (string2[I] == '*')
{
ss += cl[x].ToString();
x++;
}
else
{
ss += (list[int.Parse(s[y].ToString())][y]);
y++;
}
}
result.Add(ss);
}
return result.ToArray<string>();
}
public static string ToBinary(Int64 Decimal, int width)
{
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0)
{
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
var d = width - BinaryResult.Length;
if (d != 0) for (int i = 0; i < d; i++) BinaryResult = "0" + BinaryResult;
return BinaryResult;
}
which password cracker do you want to program? :)
how about
if string2 contains '*'
foreach(char ch in string1)
replace first * with ch,
execute FunctionName
else
print string2