i have a string that conatin 5 numbers like
'1,4,14,32,47'
i want to make from this string 5 strings of 4 number in each one
like :
'1,4,14,32'
'1,4,14,47'
'1,4,32,47'
'1,14,32,47'
'4,14,32,47'
what is the simple/faster way to do it
is the way of convert this to array unset every time diffrent entery and combine
them back to string ?
is there a simple way to do it ?
thanks
How about something like
string s = "1,4,14,32,47";
string r = String.Join(",", s.Split(',').Where((x, index) => index != 1).ToArray());
Using string.Split() you can create a string array. Loop through it, so that in each loop iteration you indicate which element should be skipped (on the first pass, ignore the first element, on the second pass, ignore the second element).
Inside that loop, create a new array that contains all elements but the one you want to skip, then use string.Join() to create each result.
Have a look at:
http://msdn.microsoft.com/en-us/magazine/ee310028.aspx Here you'll find an example in F# who will give the correct background in combinations and permutations (that's how is called what you need). There is code too, I think it's easy to translate it in C#
Example of Code in C# (text in Italian but code in English)
For those who need a more generic algorithm, here is one which gives n length subsets of m items:
private void GetPermutations()
{
int permutationLength = 4;
string s = "1,4,14,32,47";
string[] subS = s.Split(',');
int[] indexS = new int[permutationLength];
List<string> result = new List<string>();
IterateNextPerm(permutationLength, indexS, subS, result);
// Result will hold all your genberated data.
}
private void IterateNextPerm(int permutationLength, int[] pIndexes, string[] subS, List<string> result)
{
int maxIndexValue = subS.Count() - 1;
bool isCorrect = true;
for (int index = 0; index < permutationLength - 1; index++)
{
if (pIndexes[index] >= pIndexes[index + 1])
{
isCorrect = false;
break;
}
}
// Print result if correct
if (isCorrect)
{
string strNewPermutation = string.Empty;
for (int index = 0; index < permutationLength; index++)
{
strNewPermutation += subS[pIndexes[index]] + ",";
}
result.Add(strNewPermutation.TrimEnd(','));
}
// Increase last index position
pIndexes[permutationLength - 1]++;
// Check and fix if it's out of bounds
if (pIndexes[permutationLength - 1] > maxIndexValue)
{
int? lastIndexIncreased = null;
// Step backwards and increase indexes
for (int index = permutationLength - 1; index > 0; index--)
{
if (pIndexes[index] > maxIndexValue)
{
pIndexes[index - 1]++;
lastIndexIncreased = index - 1;
}
}
// Normalize indexes array, to prevent unnecessary steps
if (lastIndexIncreased != null)
{
for (int index = (int)lastIndexIncreased + 1; index <= permutationLength - 1; index++)
{
if (pIndexes[index - 1] + 1 <= maxIndexValue)
{
pIndexes[index] = pIndexes[index - 1] + 1;
}
else
{
pIndexes[index] = maxIndexValue;
}
}
}
}
if (pIndexes[0] < maxIndexValue)
{
IterateNextPerm(permutationLength, pIndexes, subS, result);
}
}
I know that it's not the nicest coding, but I've written it right now in the last half an hour so I'm sure there are things to tweek there.
Have fun coding!
var elements = string.Split(',');
var result =
Enumerable.Range(0,elements.Length)
.Reverse()
.Select(
i=>
string.Join(","
Enumerable.Range(0,i).Concat(Enumerable.Range(i+1,elements.Length - i - 1))
.Select(j=>elements[j]).ToArray() // This .ToArray() is not needed in NET 4
)
).ToArray();
your wording is pretty confusing...but the example is clear enough. just split it on commas, then remove one index, then use string.Join(",", list); to put it back together..
Related
I am trying to join the next array element together to single element from array if the element of the array is less than length 4. It should add to the next element index.
Another logic is, if the next consecutive array length is also less then 4 char then it joins the next array element also up to 3 times in total. I want to implement this. It's getting complex for me I am not understand this logic.
This is the code, here it has array on titleList, now we have to use the above logic in this array list.
#foreach (var title in randomtitle)
{
</span>#titleList.ElementAt(title)</span>
}
#code {
[Parameter]
public string theTitle { get; set; }
private string[] titleList = Array.Empty<string>();
protected override void OnParametersSet()
{
if (!string.IsNullOrEmpty(theTitle))
{
titleList = theTitle.Split(" ");
}
}
private Random random = new();
private IEnumerable<int> randomtitle =>
Enumerable.Range(0, titleList.Count() - 1) // { 0, 1, 2, 3 } generate sequence
.OrderBy(x => random.Next()) // { 3, 1, 0, 2 } random shuffle
.Take(2) // { 3, 1 } pick two
.ToList();
}
I think you are looking for a method that does following:
take a collection of strings(like a string[])
iterate each string and check if it's length is greater than or equal 4
if so, everything is fine, take it as it is
if not, append the next to the current string and check their length afterwards
if they are still not greater than or equal 4 append the next one, but max 3 times
Then this should work (not tested well though):
Demo: https://dotnetfiddle.net/2uHREv
static string[] MergeItems(IList<string> all, int minLength, int maxGroupCount)
{
List<string> list = new List<string>(all.Count);
for(int i = 0; i < all.Count; i++)
{
string current = all[i];
if(i == all.Count - 1)
{
list.Add(current);
break;
}
if (current.Length < minLength)
{
for (int ii = 1; ii < maxGroupCount && i + ii < all.Count; ii++)
{
int nextIndex = i + ii;
string next = all[nextIndex];
current = current + next;
if (current.Length >= minLength || ii+1 == maxGroupCount)
{
list.Add(current);
i = nextIndex;
break;
}
}
}
else
{
list.Add(current);
}
}
return list.ToArray();
}
In my code I have string array of 1000 indexes and it contain unique string data. Now, I want to make duplicate of some of them string element without overwriting next element. To summarize I would like to shift the array and inserting a duplicate value.
Here my code is,
for (int r = 0; r < sResultarray1.Length; r++)
{
if (sResultarray1[r] != null &&
sResultarray1[r].Contains("WP") &&
sResultarray1[r].Contains("CB") == true)
{
index = Array.IndexOf(sResultarray1, sResultarray1[r]);
for (int e = 1000; e >= index + c; e--)
{
sResultarray1[e] = sResultarray1[e - c];
}
break;
}
}
My current output is
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
My desired output is
++ST110+WP001.CB001
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
++ST130+WP001.CB001
Does anyone help me out to solve this problem?
I suggest using different collection type - List<string> instead of String[] (at least temporarily): Add, Insert ("shift and add") are not operations array has been designed for. Something like this:
using System.Linq;
...
// Temporal collection - list
List<string> list = sResultarray1.ToList();
// Downward - we don't want to check the inserted item
for (int r = list.Count - 1; r >= 0; --r) {
if (list[r] != null && list[r].Contains("WP") && list[r].Contains("CB")) {
// if you want to insert - "shift and add duplicate value" - just insert
list.Insert(r + 1, list[r]);
}
}
// back to the array
sResultarray1 = list.ToArray();
I have a list of something.
public List<Objects> obj;
The objects in this list need to be added to these other lists.
public List<Objects> objGroup1, objGroup2, objGroup3, objGroup4;
I assign them right now by doing this.
void AssignToGroups()
{
for(int i = 0; i < obj.Count ; i++)
{
//Need the first 4 for group 1 next 4 for group 2 and so on...
if(i < 4)
{
objGroup1.Add(obj[i]);
}
else if(i >= 4 && i < 8)
{
objGroup2.Add(obj[i]);
}
else if (i >= 8 && i < 12)
{
objGroup3.Add(obj[i]);
}
else if (i >= 12 && i < 16)
{
objGroup4.Add(obj[i]);
}
}
}
I'm planning on expanding and my method for grouping objects right now will fill my screen with endless if and else statements.
4 objects need to be assigned to each groups.
The objects in the group gets them in their order of arrangement.
e.g. group1 gets obj 1-4. group 2 get obj 5-8 and so on...
Does anyone have a better method of grouping objects like this?
You can utilize the Skip and Take methods.
You'll need the using System.Linq;:
objGroup1 = obj.Take(4).ToList(); //edited: use ToList() to keep the list format
objGroup2 = obj.Skip(4).Take(4).ToList();
objGroup3 = obj.Skip(8).Take(4).ToList();
objGroup4 = obj.Skip(12).Take(4).ToList();
objGroup5 = obj.Skip(16).Take(4).ToList();
Let me know if it works, since I am not able to test it now, except for the syntax.
You can also group the obj before Take(), such as
var orderedobj = obj.OrderBy(i => "some order criteria").ToList();
objGroup1 = orderedobj.Take(4);
...
I referenced my answer on How to get first N elements of a list in C#?.
EDIT:
In case you somehow do not want to use Linq, you can also use GetRange
objGroup1 = obj.GetRange(0, 4);
objGroup2 = obj.GetRange(3, 4); //since GetRange(index, count) has index starting from 0 instead of 1
objGroup3 = obj.GetRange(7, 4); //count stays the same since we always want 4 elements
objGroup4 = obj.GetRange(11, 4);
objGroup5 = obj.GetRange(15, 4);
Using Keyur's excellent answer, you could create a method that will create the groups for you, based on any source list, with a configurable group size:
private static List<List<object>> AssignToGroups(List<object> source, int groupSize)
{
var groups = new List<List<object>>();
if (source == null || groupSize < 1) return groups;
for (int i = 0; i < source.Count / groupSize; i++)
{
groups.Add(source.Skip(groupSize * i).Take(groupSize).ToList());
}
return groups;
}
Usage
private static void Main()
{
var mainList = new List<object>
{
"one", "two", "three", "four","five",
"six","seven","eight","nine","ten",
"eleven", "twelve", "thirteen", "fourteen","fifteen",
"sixteen","seventeen","eightteen","nineteen","twenty",
"twentyone", "twentytwo", "twentythree", "twentyfour","twentyfive",
"twentysix","twentyseven","twentyeight","twentynine","thirty",
"thirtyone", "thirtytwo", "thirtythree", "thirtyfour","thirtyfive",
"thirtysix","thirtyseven","thirtyeight","thirtynine","forty",
};
var groups = AssignToGroups(mainList, 4);
for (var i = 0; i < groups.Count; i++)
{
Console.WriteLine($"Group #{i + 1}: {string.Join(", ", groups[i])}");
}
Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
Output
Hi I am trying to write a method that will reverse a string array onced called. I finished my code , but only get half of the array reversed, leaving the rest unchanged, being stuck on this for hours. so I had to ask on stack as last resort.
int start;
string[] sArray = {
"Reverse", "this", "string", "type", "array"
};
int end = (sArray.Length - 1);
for (start = 0; start < sArray.Length; start++) {
sArray[start] = sArray[end - start];
Console.Write(sArray[start] + ",");
}
// The output supposed to be : array type string this Reverse
// However, I keep getting array type string type array.
// The output supposed to be : array type string this Reverse
// However, I keep getting array type string type array.
Any ideas would be appreciated.
You are missing swapping. And you can do it with half of len of array:
string[] sArray = { "Reverse", "this", "string", "type", "array" };
for (int start = 0; start < sArray.Length/2; start++ )
{
var temp = sArray[start];
sArray[start] = sArray[sArray.Length - 1 - start];
sArray[sArray.Length - 1 - start] = temp;
}
There are lots of way to do this.
First, you can use recursion. In C#-like pseudocode this will look like this:
T[] Reverse<T>(T[] input)
{
if(input.Length <= 1) return input;
return Reverse(input[0..input.Length - 1]) + input[..input.Length];
}
Next is an in-place reverse; almost what you've already done, except your for loop is twice as big as it needs to be. See what happens when you change one of the parts of your loop to start < sArray.Length / 2. Plus, you really need to swap the elements.
You are rewriting items after the HALF to the first half. try this:
int start;
string[] sArray = { "Reverse", "this", "string", "type", "array" };
string[] temp = new string[sArray.Length];
int end = (sArray.Length-1);
for (start = 0; start < sArray.Length; start++ )
{
temp[start] = sArray[end - start];
Console.Write(sArray[start]+",");
}
sArray = temp; // putting back to the original varible
Hopefully this answer makes sense, you can replace T by string if you don't understand generics. The end variable starts at the end, starts starts at the front of the array, and they progress closer to eachother until they point to the same element (for an odd sized array) or the end pointer points to something before the start pointer(for an even sized array), in either case start < end will return false, and the loop will stop.
private static void Reverse<T>(T[] items)
{
for (int start = 0, end = items.Length - 1; start < end; start++, end--)
{
Swap(items, start, end);
}
}
private static void Swap<T>(T[] items, int a, int b)
{
var help = items[a];
items[a] = items[b];
items[b] = help;
}
After half of the table you're swapping elements with already swapped.
The proper solution is:
static void Reverse()
{
string[] sArray = { "Reverse", "this", "string", "type", "array" };
int end = sArray.Length - 1;
for (int start = 0; start < (sArray.Length / 2); ++start)
{
string tmp = sArray[start];
sArray[start] = sArray[end - start];
sArray[end - start] = tmp;
}
foreach (var s in sArray)
Console.Write(s + ",");
}
Sometimes I wonder why code looks more difficult than it should be. Try `
string[] words = new string[] {"reverse", "this", "string", "type", "array"};
string[] reverse = new string[words.Length];
int start = 0;`
for(int i = words.Length - 1; i >= 0; i--){
reverse[start] = words[i];
s++;
}
foreach(string s in reverse){
Console.Write(s + ", ");
}
Hope this helps =) or use another for loop inside the for loop counting up instead of using start.
Basically comparing a string that is entered, and trying to get that position from the array.
If I initialize position to 0 then it returns the position zero of the array, if I initialize to 1 then it gives me the item in slot 1, so it's skipping the compare statement.
I also tried using (custStatus == cardStatus[i])
public static int discount(string []cardStatus, int []pDiscount, string custStatus)
{
int position= 0;
int discount;
for(int i = 0; i < 2; i++)
{
if (string.Equals(custStatus, cardStatus[i]))
position = i;
}
discount = pDiscount[position];
return discount;
}
With your code, there's no way to tell if position = 0 means custStatus was found in your cardStatus array or if no match was made at all and the default value is being used. I'd recommend either using a boolean matchFound variable or setting position = -1 and adding an extra if statement at the end either way. Either:
boolean matchFound = false;
...
if(matchFound)
{
discount = pDiscount[position];
}
or else
int position = -1;
...
if(position >= 0)
{
discount = pDiscount[position];
}
Give this a try:
public static int discount(string[] cardStatus, int[] pDiscount, string custStatus) {
var position = Array.IndexOf(cardStatus, custStatus);
return (position == -1) ? -1 : pDiscount[position];
}
public static int discount(string []cardStatus, int []pDiscount, string custStatus)
{
for(int i = 0; i < Math.Min(cardStatus.Length, pDiscount.Length); i++)
{
if (string.Equals(custStatus, cardStatus[i]))
{
return pDiscount[i];
}
}
return -1;
}
Don't be afraid to return directly from FOR-loop, it is old-school that teaches to have only one return point from method. You can have as many returns as it helps you to keep your code clean and easy to read.
And perhaps it would be better to use the following expression in for-loop as it will guard you from possible different lengths of arrays:
for (int i = 0; i < Math.Min(cardStatus.Length, pDiscount.Length; i++)
This looks ok, even though this is somewhat more straightforward:
for(int i = 0; i < cardStatus.Length; i++)
{
if (custStatus == cardStatus[i])
{
position = i;
break;
}
}
Given your question it appears to be the case that all cardStatus[i] match custStatus - did you check the input?
Also given your code what happens if there is no match? Currently you would return pDiscount[0] - that doesn't seem to be correct.