Loop to get all probabilities of combining words - c#

I have text that contains spaces.
I want all the possibilities. For example, merge a space and leave another.
For example, this is the first possibility:
the first word, then a space, the second word, then a space, then the third word.
The second possibility:
the first word, then without a space, then the second word, then a space, then the third word.
The third possibility:
the first word, then a space, then the second word, then without a space, then the third word ... etc..
I want to do this, but in a loop, especially if the number of words is more than five, six, or more.
static void Main(string[] args)
{
string test = "aaa bbb ccc";
var ch = test.Split(' ');
var t1 = ch[0] + " " + ch[1] + " " + ch[2];
var t2 = ch[0] + "" + ch[1] + " " + ch[2];
var t3 = ch[0] + " " + ch[1] + "" + ch[2];
var t4 = ch[0] + "" + ch[1] + "" + ch[2];
Console.WriteLine(t1);
Console.WriteLine(t2);
Console.WriteLine(t3);
Console.WriteLine(t4);
string test2 = "aaa bbb ccc ddd";
var ch2 = test2.Split(' ');
var z1 = ch2[0] + " " + ch2[1] + " " + ch2[2] + " " + ch2[3];
var z2 = ch2[0] + "" + ch2[1] + " " + ch2[2] + " " + ch2[3];
var z3 = ch2[0] + " " + ch2[1] + "" + ch2[2] + " " + ch2[3];
var z4 = ch2[0] + " " + ch2[1] + " " + ch2[2] + "" + ch2[3];
var z5 = ch2[0] + "" + ch2[1] + "" + ch2[2] + " " + ch2[3];
var z6 = ch2[0] + " " + ch2[1] + "" + ch2[2] + "" + ch2[3];
var z7 = ch2[0] + "" + ch2[1] + "" + ch2[2] + "" + ch2[3];
Console.WriteLine(z1);
Console.WriteLine(z2);
Console.WriteLine(z3);
Console.WriteLine(z4);
Console.WriteLine(z5);
Console.WriteLine(z6);
Console.WriteLine(z7);
Console.ReadLine();
}

So if we have n words we have n - 1 possible spaces. Let 0 be absence of space, when 1 be a presence of space:
[0, 0, 0] => Word1Word2Word3Word4
[0, 0, 1] => Word1Word2Word3 Word4
[0, 1, 0] => Word1Word2 Word3Word4
[0, 1, 1] => Word1Word2 Word3 Word4
...
[1, 1, 1] => Word1 Word2 Word3 Word4
So far so good we should enumerate all 2 ^ (n - 1) binary masks:
using System.Collections.Generic;
using System.Linq;
using System.Text;
...
private static IEnumerable<string> Solution(params string[] words) {
return Enumerable
.Range(0, 1 << (words.Length - 1))
.Select(mask => {
StringBuilder sb = new StringBuilder(words[0]);
for (int i = 0; i < words.Length - 1; ++i) {
if ((mask & (1 << i)) != 0)
sb.Append(' ');
sb.Append(words[i + 1]);
}
return sb.ToString();
});
}
Demo (fiddle):
var result = string.Join(Environment.NewLine, Solution("A", "B", "C", "D"));
Console.WriteLine(result);
Output:
ABCD
A BCD
AB CD
A B CD
ABC D
A BC D
AB C D
A B C D

The code you provided works for a limited number of words, but becomes impractical as the number of words increases. A more efficient way to generate all possibilities of a string containing spaces is to use loops and recursion. Here's an example of a function that takes a string and generates all possible combinations of that string (with and without spaces):
private static List<string> GenerateCombinations(string[] words, int index)
{
if (index == words.Length)
{
return new List<string> { "" };
}
var result = new List<string>();
var subCombinations = GenerateCombinations(words, index + 1);
foreach (var subCombination in subCombinations)
{
result.Add(words[index] + subCombination);
result.Add(words[index] + " " + subCombination);
}
return result;
}
You can call this function with the string you want to generate combinations for:
string test = "aaa bbb ccc ddd";
var words = test.Split(' ');
var combinations = GenerateCombinations(words, 0);
foreach(var combination in combinations)
{
Console.WriteLine(combination);
}
The function uses recursion to generate all possible combinations of strings. The index parameter is used to keep track of the current word in the word array, and the recursion stops when the index equals the length of the word array. The function uses two lists to store combinations: one for the current index and one for the next index. The current list is added to the next list in two ways, with and without spaces.
This approach will work for any number of words and will generate all possible combinations efficiently.

Related

C# multiple increments

I have, code who do for me "x + y = z"
if (command.Contains("+")) // string polecenie = "";'
{
polecenie = "{" + command + ")";
polecenie = polecenie.Replace("+", "}(");
double a = Convert.ToDouble(Between(polecenie, "{", "}"));
double b = Convert.ToDouble(Between(polecenie, "(", ")"));
double wyn = a + b;
richTextBox1.Text += a + " + " + b + " is " + wyn + "\r\n";
}
And when 'command' is "4+5","3 + 4" or something like this code works, but when i try to do "4 + 3 + 23" it don't work. Final string with starting 'command' "4+5+6", polecenie is: "{4}(5}(6)"... The Between Method:
public string Between(string content, string First, string Last)
{
string end = "";
int Plc1 = content.IndexOf(First) + First.Length;
int Plc2 = content.IndexOf(Last);
end = content.Substring(Plc1, Plc2 - Plc1);
return end;
}
How can I do that? (I want it to work with all possible additions ("4+4","34+5+54","43+4+65+54"...)
You could use the DataTable object to not re-invent the wheel.
richTextBox1.Text = string.Format("{0} is {1}\r\n", command,
(new System.Data.DataTable()).Compute(command, string.Empty));
This would support +, -, *, / and % (mod) operators. For more: https://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx

String magically cuts by itself

I don't understand what is going on. Recently I took this code and edited it a bit. I've found a bug so I've tried to debug it and met weird behaviour. Somewhy 2 strings created from 2 different char arrays consisting of same letters aren't equal and also debug string is cutted.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AlphanumericComparer : IComparer<string>
{
public int Compare(string s1, string s2)
{
if (s1 == null || s2 == null)
return 0;
int len1 = s1.Length;
int len2 = s2.Length;
int i1 = 0;
int i2 = 0;
while (i1 < len1 && i2 < len2)
{
char c1 = s1[i1];
char c2 = s2[i2];
char[] chunk1 = new char[len1];
int j1 = 0;
char[] chunk2 = new char[len2];
int j2 = 0;
do
{
Debug.Log("1: " + i1 + " _ " + j1 + " _ " + c1); // Seems to be OK.
chunk1[j1++] = c1;
i1++;
if (i1 < len1)
c1 = s1[i1];
else
break;
} while (char.IsDigit(c1) == char.IsDigit(chunk1[0]));
do
{
Debug.Log("2: " + i2 + " _ " + j2 + " _ " + c2); // Seems to be OK.
chunk2[j2++] = c2;
i2++;
if (i2 < len2)
c2 = s2[i2];
else
break;
} while (char.IsDigit(c2) == char.IsDigit(chunk2[0]));
string str1 = new string(chunk1);
string str2 = new string(chunk2);
Debug.Log(str1.CompareTo(str2) + " " + str1 + " " + str2); // "1"?! And also why is string cutted?!
int result;
if (char.IsDigit(chunk1[0]) && char.IsDigit(chunk2[0]))
{
result = int.Parse(str1).CompareTo(int.Parse(str2));
//Debug.Log(s1 + " _ " + s2 + " _ " + int.Parse(str1) + " _ " + int.Parse(str2) + " _ " + result);//tmp
Debug.Log(string.Format("{0}, {1}, {2}, {3}, {4}", s1, s2, int.Parse(str1), int.Parse(str2), result));//tmp
}
else
{
result = str1.CompareTo(str2);
//Debug.Log(s1 + " _ " + s2 + " _ " + str1 + " _ " + str2 + " _ " + result);//tmp
Debug.Log(string.Format("{0}, {1}, {2}, {3}, {4}", s1, s2, str1, str2, result));//tmp
}
if (result != 0)
return result;
}
return len1 - len2;
}
}
I've tried to reload all IDEs but it has brought nothing. My strings which I compare:
string[] test = new string[] { "qwe45", "qwe13a" };
For the next string sorting works as expected and behaviour differs but cutted debug string bug is still there:
string[] test = new string[] { "qwe45", "qwe13" };
What am I doing wrong or if I am not, how to workaround this?
UPDATE:
Also if I split like this:
Debug.Log(str1);
Debug.Log(str2);
it shows right stuff, but CompareTo still returns some garbage.
I struggle to understand what the code is trying to accomplish, but it seems to me that your declaration char[] chunk1 = new char[len1]; creates a variable that is one character too short.
len1 is the length of the first input string, in your example ("qwe45") 5. So chunk1 will have five chars of memory space, which allows four chars of text plus the terminating 0.
Then you copy it into str1 with string str1 = new string(chunk1);, which means that str1 will now be one char shorter. Isn't that the char you are missing?

StreamWriter Issue: Line breaks

First let me present the code:
private void AdicionarFormula(string x, string y, string Materia)
{
MessageBox.Show("%" + x + " = " + y + "#" + Materia);
StreamWriter Escritor = new StreamWriter(Properties.Settings.Default.ArquivoDeFormulas, true);
Escritor.WriteLine("%" + x + " = " + y + "#" + Materia);
Escritor.Close();
LerFormulas(true);
}
The issue is: instead of the output being "%x = y#Materia" it is actually "
%x = y
#Materia"
I dont want it to create a new line for "#Materia".
Your parameter 'y' contains char a newline. For example, try it in your code:
string.Format("%" + x + " = " + y + "#" + Materia).Replace("\n","")

Better way of doing it - GetFiles - c#

I'm trying to get all files in a directory but I want them associated with numbers. Now, I have this:
string[] ficheiro = Directory.GetFiles(#"C:\Users\David\Documents\Jogos\Jogos de emuladores\Roms GB\", "*.gba");
{
Console.WriteLine ("F1" + " - " + Path.GetFileNameWithoutExtension (ficheiro[0]));
}
Console.ReadKey ();
When I reach 10 files I will have a shortcut to flip a page to get more files (10 per page). I will list all files by hand. Like this:
Console.WriteLine ("F2" + " - " + Path.GetFileNameWithoutExtension (ficheiro[1]));
Console.WriteLine ("F3" + " - " + Path.GetFileNameWithoutExtension (ficheiro[2]));
Is there a better way of doing it?
You need to use a loop. You cannot do all of them "by hand" because you do not necessarily know how many there are.
var files = Directory.GetFiles(#"C:\Your\Directory\Path", "*.gba");
var count = 0;
foreach (var file in files)
{
if (count % 10 == 0 && count != 0)
{
Console.ReadLine();
}
count++;
Console.WriteLine("F{0} - {1}", count, Path.GetFileNameWithoutExtension(file));
}
Console.ReadLine();
You can iterate through the array with a for-loop :
string[] ficheiros = Directory.GetFiles(#"C:\Users\David\Documents\Jogos\Jogos de emuladores\Roms GB\", "*.gba");
for (int i = 0; i < ficheiros.Length; i++)
{
Console.WriteLine("F{0} - {1}", i + 1, Path.GetFileNameWithoutExtension(ficheiros[i]));
}
Console.ReadKey();
The key is to identify the repeating part and extract a pattern from it :
//only these changed V V
Console.WriteLine ("F2" + " - " + Path.GetFileNameWithoutExtension (ficheiro[1]));
Console.WriteLine ("F3" + " - " + Path.GetFileNameWithoutExtension (ficheiro[2]));
// just replace them and put it inside an appropriate loop, in this case a for-loop
for(int i = 0; i < ficheiro.Length; i++)
Console.WriteLine ("F" + (i+1) + " - " + Path.GetFileNameWithoutExtension (ficheiro[i]));
int i = 0;
var ficheiro = from s in Directory.GetFiles(#"C:\temp\", "*.*")
select ("F"+ i++ + "-" + s);

Adding and Changing Items in a array C#

I was wondering if you cloud help me?
I have an array that consist of items and prices and qty.
If the item exist it the array it must update the price and the qty, If it doesn't exits it must be added
Here is my code that i have tried:
if (line.Contains(ItemCode))
{
string[] details = line.Split(new string[] { "|" }, StringSplitOptions.None);
{
for (int i = 0; i < details.Length; i++)
{
if (details[i].Contains(ItemCode))
{
string[] line_details = details[i].Split(',');
string replace = line_details[2].Trim() + "," + line_details[3].Trim();
double NewQty = double.Parse(Qty) + double.Parse(line_details[2]);
double NewPrice = (double.Parse(UnitPrice) * double.Parse(Qty));
double NewUnitPrice = NewPrice + double.Parse(line_details[3]);
string new_replace = NewQty + "," + NewUnitPrice;
line = line.Replace(replace, new_replace);
}
}
}
}
else
{
line = line + "\"Detail\",0," + Qty + "," + (double.Parse(UnitPrice) * double.Parse(Qty)) + "," + InclusivePrice + ",\"" + UnitUsed + "\"," + TaxType + "," + DiscountType + "," + DiscountPercentage + ",\"" + ItemCode + "\",\"" + Description + "\"," + SearchType + "," + "\"\"" + ",\"" + MultiStore + "\"|" + Environment.NewLine;
}
it is not working could you maby assist me on this?
Arrays in C# cannot have entries added to them after being initialised. You're better off using a List<String> instead, where you can add and remove entries from the list. Alternatively consider a Dictionary<Int32, String>, which would let you use the ItemCode as an identifier to make finding a given entry easier.
As a furthur point, instead of storing all your item data in a delimited string, make a new Class for them, with the various details as properties, and then you can use a theoretical Dictionary<Int32, ItemObject> for better clarity.

Categories