How to get all palindrome substrings from the given string "ab12321bakjjkh3432"? - c#

I tried with this code, but it only displays whether a given string is palindrome or not. I want to extract and display all the possible palindrome substrings in the given string.
public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
Expected output:
232
12321
b12321b
ab12321ba
343
kjjk

Here is an example:
using System;
public class Program
{
private static bool istPalindrom(string word){
int i1 = 0;
int i2 = word.Length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
private static void FindPalindromes(string s)
{
// Assume a palindrome string is at least 2 characters
const int MinLength = 2;
if (s.Length <= MinLength)
{
return;
}
// Test all substrings by removing i first characters
for (int i = 0; i < s.Length - MinLength; i++)
{
string sub = s.Substring(i);
if (istPalindrom(sub))
{
Console.WriteLine($"Found palindrome: {sub}");
}
}
// Test all strings by the last character
FindPalindromes(s.Substring(0, s.Length - 1));
}
public static void Main()
{
FindPalindromes("ab12321bakjjkh3432");
}
}
which uses your istPalindrom method to check (but with string instead of char[]). This tests all possible substrings of the given string. There are probably more efficient ways to do this, taking advantage of a palindrome of length n must contain a palindrom of length n - 2, meaning one could find all palindromes of length 3 and 4, and then try expanding those strings.
Output:
Found palindrome: 343
Found palindrome: kjjk
Found palindrome: ab12321ba
Found palindrome: b12321b
Found palindrome: 12321
Found palindrome: 232

Palindrome initial string
public static string PalindromeString { get; set; } = "ab12321bakjjkh3432";
Actual logic to print palindrome string from given string
for (float index = 0; index < PalindromeString.Length; index += (float).5)
{
// set nearest element radius
// on both left and right side
float palindromeNearestElementRadius = index - (int)index;
// if there is need to compare indexes and if it has desired elements
// and both sides of value matches for Example (212) etc.....
while ((index + palindromeNearestElementRadius) < PalindromeString.Length
&& (index - palindromeNearestElementRadius) >= 0
&& PalindromeString[(int)(index - palindromeNearestElementRadius)]
== PalindromeString[(int)(index + palindromeNearestElementRadius)])
{
var element = PalindromeString.Substring((int)(index - palindromeNearestElementRadius),
(int)(index + palindromeNearestElementRadius + 1) -
(int)(index - palindromeNearestElementRadius));
if (element.Length != 1)
{
Console.WriteLine(element);
}
// increasing the element radius by 1
// to point towards the
// next elements for both sides to move forward our comparision
//
palindromeNearestElementRadius++;
}
Output
232
12321
b12321b
ab12321ba
jj
kjjk
343

Related

Rotating a multiline string 90 degrees - lines become columns

Say I have a string like
Line 1
Line 2
I want to turn this string 90 degrees clockwise, so that it becomes
LL
ii
nn
ee
12
The rotation needs to be performed only once such that it is in effect 'turning lines into columns.' Performing it twice should give the original string. (If it was truly rotating by 90 degrees, it would have to be repeated four times to arrive back at the original.)
using System;
using System.Collections;
using System.Collections.Generic;
namespace rotateString
{
class Program
{
static void Main(string[] args)
{
var strings = new string[] { "Line 1", "Line 2" };
var lines = new List<string>();
var done = false;
var j = 0;
do
{
var line = "";
for (var i = 0; i < strings.Length; ++i)
{
var s = strings[i];
if (j >= s.Length)
{
done = true;
break;
}
line += s[j];
}
lines.Add(line);
++j;
} while (!done);
for(int i=0; i < lines.Count; ++i)
{
Console.WriteLine(string.Format("{0} : '{1}'", i, lines[i]));
}
}
}
}
Output:
0 : 'LL'
1 : 'ii'
2 : 'nn'
3 : 'ee'
4 : ' '
5 : '12'
6 : ''
Note that this pretty much assumes the strings are all the same length. Adjusting it to work with the longest string length is trivial.
Using a StringBuilder would be a bit more efficient but, unless you're working with a lot of very long strings, you'll never see the difference in performance.
This was interesting to try out and write. I haven't spent time on validation and characters, but I was trying to see if I can write something that is somewhat "compact" (challenge to myself mostly in evening hours).
#KayZed I will also run your implementation, I see you did some more validations about the inputs.
#3Dave I see we had similar ideas about this ;)
My idea around this was a projection of the input strings (plus now I hard-coded the length of the Span<char>, that calculation can be made simple) into the "flattened" structure of all characters with the offset of the index based on the number of inputs.
My "solution":
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
var inputs = new[] { "Short", "Line 1", "Line 2", "Much longer line 3", "🧐" };
Rotate(inputs);
}
public static void Rotate(IReadOnlyCollection<string> aValues)
{
Span<char> chars = stackalloc char[100];
var offset = 0;
foreach (var value in aValues)
{
var index = 0;
foreach (char character in value)
{
chars[index + offset] = character;
index += aValues.Count;
}
offset++;
}
var position = 0;
foreach (char character in chars)
{
Console.Write(character == default(char) ? ' ' : character);
Console.Write(' ');
if (position == aValues.Count - 1)
{
Console.WriteLine();
position = 0;
continue;
}
position++;
}
}
}
I probably missed some edge cases (and didn't handle the "special" characters), but hope this gives an idea on some "optimisations".
The output:
S L L M �
h i i u �
o n n c
r e e h
t
1 2 l
o
n
g
e
r
l
i
n
e
3
It will need to add leading spaces (i.e. columns which were preceding shorter lines in the original string.) This method gives you an option to make this visible (fillChar - several options provided as constants.)
Also the additional ReverseLineOrder method reverses the line order in case you would want to rotate 90 degrees, reversing all lines.
using System;
using System.Globalization;
using System.Text;
namespace Library.Text
{
public static class TextRotate
{
public const char Space = ' ';
public const char MiddleDot = '\u00b7';
public const char Circle = '\u25cb';
public const char BlackSquare = '\u25a0';
public const char NoBreakSpace = '\u00a0';
public static string LinesToColumns(string s, char fillChar = Space)
{
// A line feed at the end of the text is not seen as content.
// However, if the text ends in a line feed, we make sure the output ends in one, too.
bool endsWithNewline = s.EndsWith(Environment.NewLine);
string[] linesIn = s.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
int[][] textElements = new int[linesIn.Length][];
int longestLine_chars = 0;
int longestLine_elems = 0; // The longest line, in text elements
for (int l = 0; l < linesIn.Length; l++)
{
string line = linesIn[l];
if (line.Length > longestLine_chars)
{
longestLine_chars = line.Length;
}
var elems = StringInfo.ParseCombiningCharacters(line); // Gets indices of surrogate pairs, combining characters etc.
if (elems.Length > longestLine_elems)
{
longestLine_elems = elems.Length;
}
textElements[l] = elems;
}
// Go through columns (columns in the input text, and columns in terms of text elements - NOT chars)
string[] columns = new string[longestLine_elems];
var builder = new StringBuilder(longestLine_chars * linesIn.Length + Math.Max(longestLine_chars, linesIn.Length) * Environment.NewLine.Length);
for (int column = 0; column < longestLine_elems; column++)
{
builder.Clear();
System.Diagnostics.Debug.Assert(builder.Length == 0);
int cutoff = 0;
for (int l = 0; l < linesIn.Length; l++)
{
// Is the line long enough to reach to this column?
int[] lineTextElements = textElements[l];
int textElementsInLine = lineTextElements.Length;
if (textElementsInLine > column)
{
int firstCharIndex = lineTextElements[column];
if (column + 1 < textElementsInLine)
{
int nrOfChars = lineTextElements[column + 1] - firstCharIndex;
builder.Append(linesIn[l], firstCharIndex, nrOfChars);
}
else
{
builder.Append(linesIn[l], firstCharIndex, linesIn[l].Length - firstCharIndex);
}
cutoff = builder.Length;
}
else
{
builder.Append(fillChar);
}
}
// Trim the fill char off line endings (for when rotating back)
while (cutoff > 0 && builder[cutoff - 1] == fillChar)
{
cutoff--;
}
// Resulting column
columns[column] = builder.ToString(0, cutoff);
}
// Turn the columns into lines
builder.Clear();
foreach (var c in columns)
{
builder.AppendLine(c);
}
if (!endsWithNewline && builder.Length > 0)
{
builder.Length -= Environment.NewLine.Length;
}
return builder.ToString();
}
public static string ReverseLineOrder(string s)
{
// A line feed at the end of the text is not seen as content.
// However, if the text ends in a line feed, we make sure the output ends in one, too.
bool endsWithNewline = s.EndsWith(Environment.NewLine);
string[] linesIn = s.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
var builder = new StringBuilder(s.Length);
for (int l = linesIn.Length - (endsWithNewline ? 2 : 1); l >= 0; l--)
{
builder.AppendLine(linesIn[l]);
}
if (!endsWithNewline && builder.Length > 0)
{
builder.Length -= Environment.NewLine.Length;
}
return builder.ToString();
}
}
}

Getting number of possible anagrams from a generic string, need a fast solution

I am currently working on an assignment where I need to write a small program that will take a generic string and should output how many possible anagrams that could be generated from the string.
The string that is the input can be up to 100 chars long and could include both lowercase and uppercase, in this case both lowercase and uppercase are considered distinct. The output should only be how many possible combinations, so I don't need to output the actual anagrams.The maximum timelimit is 1 second per string.
I have tried a number of diffrent ways of doing this, but one conclusion is that this should be solvable using some type of mathemathical algorithm.
The latest code I have tried with is this:
static void Main(string[] args)
{
string line;
while ((line = Console.ReadLine()) != null)
{
var uniqueStringArr = removeDuplicates(line);
Console.WriteLine(countDistinctPermutations(new string(uniqueStringArr)));
}
}
private static char[] removeDuplicates(string line)
{
var list = line.ToList();
return list.Distinct().ToArray();
}
static int MAX_CHAR = 100;
// Utility function to find factorial of n.
static int factorial(int n)
{
int fact = 1;
for (int i = 2; i <= n; i++)
fact = fact * i;
return fact;
}
// Returns count of distinct permutations
// of str.
static int countDistinctPermutations(String str)
{
int length = str.Length;
int[] freq = new int[MAX_CHAR];
// finding frequency of all the lower case
// alphabet and storing them in array of
// integer
for (int i = 0; i < length; i++)
if (str[i] >= 'a')
freq[str[i] - 'a']++;
// finding factorial of number of appearances
// and multiplying them since they are
// repeating alphabets
int fact = 1;
for (int i = 0; i < MAX_CHAR; i++)
fact = fact * factorial(freq[i]);
// finding factorial of size of string and
// dividing it by factorial found after
// multiplying
return factorial(length) / fact;
}
The thing is that this code does not give the correct answer for all my testcases.
The following sample data was provided for me :
Input string | Number of possible anagrams
at | 2
ordeals | 5040
abcdefghijklmnopqrstuvwxyz | 403291461126605635584000000
abcdefghijklmabcdefghijklm | 49229914688306352000000
abcdABCDabcd | 29937600
My code fixes the first two examples, but I get completly diffrent numbers for the other 3.
Is there anyone who can help me with this problem because I am running out of ideas ?
/Andreas
static BigInteger Factorial(long x)
{
return x <= 1 ? 1 : x * Factorial(x-1);
}
private static BigInteger NumberOfDistinctPermutationOf(string str)
{
BigInteger dividend = Factorial(str.Length);
foreach (char chr in str)
{
dividend /= Factorial(str.Count(c => c == chr));
str = str.Replace(chr.ToString(), string.Empty);
}
return dividend;
}
Description:
BigInteger Struct: Represents an arbitrarily large signed integer.
Enumerable.Count Method: Returns a number that represents how many elements in the specified sequence satisfy a condition.
String.Replace(String, String) Method: Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
GetNumberOfDistinctPermutation Method: Divides factorial of the length of the string by factorial of the number of occurrences of the char and then removes all occurrences of the char, for each char in the string.
static void Main(string[] args)
{
string line;
while ((line = Console.ReadLine()) != null)
{
Console.WriteLine($"{line} -> {countDistinctPermutations(line)}");
}
}
static BigInteger factorial(int n)
{
double fact = 1;
for (int i = 2; i <= n; i++)
fact = fact * i;
return fact;
}
static BigInteger countDistinctPermutations(String str)
{
// get a collection of {letter,occurences}
var duplicates = Array.GroupBy(p => p).Select(x => new { x.Key, count = x.Count() }).Where(x => x.count > 1);
BigInteger result = factorial(str.Length);
// foreach letter where occurence > 1 divide total permutations by the permutations for the occurence value (occurrence!)
foreach (var d in duplicates)
{
result /= factorial(d.count);
}
return result;
}
I only write code for a week so it's not that pretty but it works 100%.
static void Main(string[] args)
{
string inputData = Console.ReadLine();
Console.WriteLine(Solution(inputData));
}
static char[] convert(string text) // converting string to char[]
{
char[] newString = new char[text.Length];
for (int i = 0; i < text.Length; i++)
{
newString[i] = text[i];
}
return newString;
}
static double CalculateFctorial(double number) // calc. factorial
{
double factorial = 1;
for (int i = 1; i <= number; i++)
factorial *= i;
return factorial;
}
static int CountOcc(string text, char zet) // counting occurrences
{
int count = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == zet)
{
count++;
}
}
return count;
}
static double Solution(string text) // the soluton, counting occurences of
// each char in string and each factorial
{
double net = 0;
double sol = 1;
char[] newText = convert(text);
for (int i = 0; i <= newText.Length; i++)
{
if (text.Length > 0)
{
net = CountOcc(text, newText[i]);
sol = sol * CalculateFctorial(net);
if (newText[i] == text[0])
{ text = text.Trim(text[0]); }
}
}
double solution = CalculateFctorial(newText.Length) / sol;
return solution;
}

How to split characters of string equally between buttons?

I have an array of string elements of various words. I need the characters of each word be split equally into the text component of 3 buttons. For example, the array could hold the elements "maybe", "his", "car". In each game one of these words will be pulled from the array and its characters divided into the 3 buttons. For example, button 1 will have "ma", button 2 will have "yb" and button 3 "e" (for the word maybe). I then hide the text element of one button for the user to drag and drop the correct missing letter(s) into the space. The purpose of the game is to help children learn to spell. Does anyone know how I could go about dividing the characters equally into the 3 buttons?
Here's a function that would split the word into the amount of segments you want. You can then iterate over that list to set each segment to a button.Text.
public List<string> SplitInSegments(string word, int segments)
{
int wordLength = word.Length;
// The remainder tells us how many segments will get an extra letter
int remainder = wordLength % segments;
// The base length of a segment
// This is a floor division, because we're dividing ints.
// So 5 / 3 = 1
int segmentLength = wordLength / segments;
var result = new List<string>();
int startIndex = 0;
for (int i = 0; i < segments; i++)
{
// This segment may get an extra letter, if its index is smaller then the remainder
int currentSegmentLength = segmentLength + (i < remainder ? 1 : 0);
string currentSegment = word.Substring(startIndex, currentSegmentLength);
// Set the startindex for the next segment.
startIndex += currentSegmentLength;
result.Add(currentSegment);
}
return result;
}
usage:
// returns ["ma", "yb", "e"]
var segments = SplitInSegments("maybe", 3);
Edit
I like the fact that this is for teaching children. So here comes.
Regarding your question on splitting the string based on specific letter sequences: After you've split the string using regex, you will have an array of strings. Then determine the amount of items in the splitted string and concatenate or split further based on the number of segments:
// sequences to split on first
static readonly string[] splitSequences = {
"el",
"ol",
"bo"
};
static readonly string regexDelimiters = string.Join('|', splitSequences.Select(s => "(" + s + ")"));
// Method to split on sequences
public static List<string> SplitOnSequences(string word)
{
return Regex.Split(word, regexDelimiters).Where(s => !string.IsNullOrEmpty(s)).ToList();
}
public static List<string> SplitInSegments(string word, int segments)
{
int wordLength = word.Length;
// The remainder tells us how many segments will get an extra letter
int remainder = wordLength % segments;
// The base length of a segment
// This is a floor division, because we're dividing ints.
// So 5 / 3 = 1
int segmentLength = wordLength / segments;
var result = new List<string>();
int startIndex = 0;
for (int i = 0; i < segments; i++)
{
// This segment may get an extra letter, if its index is smaller then the remainder
int currentSegmentLength = segmentLength + (i < remainder ? 1 : 0);
string currentSegment = word.Substring(startIndex, currentSegmentLength);
// Set the startindex for the next segment.
startIndex += currentSegmentLength;
result.Add(currentSegment);
}
return result;
}
// Splitword will now always return 3 segments
public static List<string> SplitWord(string word)
{
if (word == null)
{
throw new ArgumentNullException(nameof(word));
}
if (word.Length < 3)
{
throw new ArgumentException("Word must be at least 3 characters long", nameof(word));
}
var splitted = SplitOnSequences(word);
var result = new List<string>();
if (splitted.Count == 1)
{
// If the result is not splitted, just split it evenly.
result = SplitInSegments(word, 3);
}
else if (splitted.Count == 2)
{
// If we've got 2 segments, split the shortest segment again.
if (splitted[1].Length > splitted[0].Length
&& !splitSequences.Contains(splitted[1]))
{
result.Add(splitted[0]);
result.AddRange(SplitInSegments(splitted[1], 2));
}
else
{
result.AddRange(SplitInSegments(splitted[0], 2));
result.Add(splitted[1]);
}
}
else // splitted.Count >= 3
{
// 3 segments is good.
result = splitted;
// More than 3 segments, combine some together.
while (result.Count > 3)
{
// Find the shortest combination of two segments
int shortestComboCount = int.MaxValue;
int shortestComboIndex = 0;
for (int i = 0; i < result.Count - 1; i++)
{
int currentComboCount = result[i].Length + result[i + 1].Length;
if (currentComboCount < shortestComboCount)
{
shortestComboCount = currentComboCount;
shortestComboIndex = i;
}
}
// Combine the shortest segments and replace in the result.
string combo = result[shortestComboIndex] + result[shortestComboIndex + 1];
result.RemoveAt(shortestComboIndex + 1);
result[shortestComboIndex] = combo;
}
}
return result;
}
Now when you call the code:
// always returns three segments.
var splitted = SplitWord(word);
Here is another approach.
First make sure that the word can be divided by the desired segments (add a dummy space if necessary) , then use a Linq statement to get your parts and when adding the result trim away the dummy characters.
public static string[] SplitInSegments(string word, int segments)
{
while(word.Length % segments != 0) { word+=" ";}
var result = new List<string>();
for(int x=0; x < word.Count(); x += word.Length / segments)
result.Add((new string(word.Skip(x).Take(word.Length / segments).ToArray()).Trim()));
return result.ToArray();
}
You can split your string into a list and generate buttons based on your list. The logic for splitting the word into a string list would be something similar to this:
string test = "maybe";
List list = new List();
int i = 0, len = 2;
while(i <= test.Length)
{
int lastIndex = test.Length - 1;
list.Add(test.Substring(i, i + len > lastIndex? (i + len) - test.Length : len));
i += len;
}
HTH

How to improve efficiency - string representation of an integer using standard incremental routine

I created a thread for this but then deleted it as I wasnt making myself clear.
This routine (my code) gives me the string representation of currentCombination.
using System;
using System.Collections.Generic;
namespace SlowGen
{
class MyClass
{
private List<char> _data = new List<char>();
private List<char> _c;
public MyClass(List<char> chars, Int64 currentCombination)
{
_c = chars;
_data.Add(_c[0]);
for (int i = 0; i < currentCombination - 1; i++)
{
if (i < currentCombination - _c.Count)
IncrementFast();
else
Increment();
}
}
public void Increment()
{
Increment(0);
}
public void Increment(int charIndex)
{
if (charIndex + 1 > _data.Count)
_data.Add(_c[0]);
else
{
if (_data[charIndex] != _c[_c.Count - 1])
{
_data[charIndex] = _c[_c.IndexOf(_data[charIndex]) + 1];
}
else
{
_data[charIndex] = _c[0];
Increment(charIndex + 1);
}
}
}
public void IncrementFast()
{
IncrementFast(0);
}
public void IncrementFast(int charIndex)
{
if (charIndex + 1 > _data.Count)
_data.Add(_c[0]);
else
{
if (_data[charIndex] != _c[_c.Count - 1])
{
_data[charIndex] = _c[_c.Count-1];
}
else
{
_data[charIndex] = _c[0];
Increment(charIndex + 1);
}
}
}
public string Value
{
get
{
string output = string.Empty;
foreach (char c in _data)
output = c + output;
return output;
}
}
}
}
Using this example would create A,B,C,AA,AB,AC,BA etc..
List<char> a = new List<char>();
a.Add('A');
a.Add('B');
a.Add('C');
MyClass b = new MyClass(a,3);
//b.Value: C
MyClass c = new MyClass(a,4);
//c.Value: AA
Now I have this code, which is much more efficient, but the patter differs
static void Main(string[] args)
{
char[] r = new char[] { 'A', 'B', 'C' };
for (int i = 0; i <= 120; i++)
{
string xx = IntToString(i, r);
Console.WriteLine(xx);
System.Threading.Thread.Sleep(100);
}
Console.ReadKey();
}
public static string IntToString(int value, char[] baseChars)
{
string result = string.Empty;
int targetBase = baseChars.Length;
do
{
result = baseChars[value % targetBase] + result;
value = value / targetBase;
}
while (value > 0);
return result;
}
It outputs A,B,C,BA,BB,
I need the sequence of the first section of code with the elegance of the second, can anyone advise?
Thankyou
You need the behaviour to change for columns besides the units column, as you've no doubt noticed. Since the values for non-units column you see are 1 too high, you need to compensate by subtracting 1 first. Or at least that's what seemed to work here:
public static string IntToString(int value, char[] baseChars)
{
string result = string.Empty;
int targetBase = baseChars.Length;
do
{
int currentValue = value % targetBase;
result = baseChars[currentValue] + result;
value = value - currentValue; //possibly not necessary due to integer division rounding down anyway
value = value / targetBase;
value = value - 1;
}
while (value > -1);
return result;
}
Here are some worked examples:
6 with targetBase 2 is AAA:
6%2 is 0, place A on right, half to 3, subtract 1 to 2
2%2 is 0, place A, half to 1, subtract 1 to 0
0%2 is 0, place A, we're done
5 with targetBase 2 is BB:
5%2 is 1, place B on right, subtract 1, half to 2, subtract 1 to 1
1%2 is 1, place B, subtract 1, we're done
7 with target base 3 is BB:
7%3 is 1, place B on right, subtract 1 to 6, 1/3 to 2, subtract 1 to 1
1%3 is 1, place B on right, subtract 1, we're done

Iterating through the Alphabet - C# a-caz

I have a question about iterate through the Alphabet.
I would like to have a loop that begins with "a" and ends with "z". After that, the loop begins "aa" and count to "az". after that begins with "ba" up to "bz" and so on...
Anybody know some solution?
Thanks
EDIT: I forgot that I give a char "a" to the function then the function must return b. if u give "bnc" then the function must return "bnd"
First effort, with just a-z then aa-zz
public static IEnumerable<string> GetExcelColumns()
{
for (char c = 'a'; c <= 'z'; c++)
{
yield return c.ToString();
}
char[] chars = new char[2];
for (char high = 'a'; high <= 'z'; high++)
{
chars[0] = high;
for (char low = 'a'; low <= 'z'; low++)
{
chars[1] = low;
yield return new string(chars);
}
}
}
Note that this will stop at 'zz'. Of course, there's some ugly duplication here in terms of the loops. Fortunately, that's easy to fix - and it can be even more flexible, too:
Second attempt: more flexible alphabet
private const string Alphabet = "abcdefghijklmnopqrstuvwxyz";
public static IEnumerable<string> GetExcelColumns()
{
return GetExcelColumns(Alphabet);
}
public static IEnumerable<string> GetExcelColumns(string alphabet)
{
foreach(char c in alphabet)
{
yield return c.ToString();
}
char[] chars = new char[2];
foreach(char high in alphabet)
{
chars[0] = high;
foreach(char low in alphabet)
{
chars[1] = low;
yield return new string(chars);
}
}
}
Now if you want to generate just a, b, c, d, aa, ab, ac, ad, ba, ... you'd call GetExcelColumns("abcd").
Third attempt (revised further) - infinite sequence
public static IEnumerable<string> GetExcelColumns(string alphabet)
{
int length = 0;
char[] chars = null;
int[] indexes = null;
while (true)
{
int position = length-1;
// Try to increment the least significant
// value.
while (position >= 0)
{
indexes[position]++;
if (indexes[position] == alphabet.Length)
{
for (int i=position; i < length; i++)
{
indexes[i] = 0;
chars[i] = alphabet[0];
}
position--;
}
else
{
chars[position] = alphabet[indexes[position]];
break;
}
}
// If we got all the way to the start of the array,
// we need an extra value
if (position == -1)
{
length++;
chars = new char[length];
indexes = new int[length];
for (int i=0; i < length; i++)
{
chars[i] = alphabet[0];
}
}
yield return new string(chars);
}
}
It's possible that it would be cleaner code using recursion, but it wouldn't be as efficient.
Note that if you want to stop at a certain point, you can just use LINQ:
var query = GetExcelColumns().TakeWhile(x => x != "zzz");
"Restarting" the iterator
To restart the iterator from a given point, you could indeed use SkipWhile as suggested by thesoftwarejedi. That's fairly inefficient, of course. If you're able to keep any state between call, you can just keep the iterator (for either solution):
using (IEnumerator<string> iterator = GetExcelColumns())
{
iterator.MoveNext();
string firstAttempt = iterator.Current;
if (someCondition)
{
iterator.MoveNext();
string secondAttempt = iterator.Current;
// etc
}
}
Alternatively, you may well be able to structure your code to use a foreach anyway, just breaking out on the first value you can actually use.
Edit: Made it do exactly as the OP's latest edit wants
This is the simplest solution, and tested:
static void Main(string[] args)
{
Console.WriteLine(GetNextBase26("a"));
Console.WriteLine(GetNextBase26("bnc"));
}
private static string GetNextBase26(string a)
{
return Base26Sequence().SkipWhile(x => x != a).Skip(1).First();
}
private static IEnumerable<string> Base26Sequence()
{
long i = 0L;
while (true)
yield return Base26Encode(i++);
}
private static char[] base26Chars = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
private static string Base26Encode(Int64 value)
{
string returnValue = null;
do
{
returnValue = base26Chars[value % 26] + returnValue;
value /= 26;
} while (value-- != 0);
return returnValue;
}
The following populates a list with the required strings:
List<string> result = new List<string>();
for (char ch = 'a'; ch <= 'z'; ch++){
result.Add (ch.ToString());
}
for (char i = 'a'; i <= 'z'; i++)
{
for (char j = 'a'; j <= 'z'; j++)
{
result.Add (i.ToString() + j.ToString());
}
}
I know there are plenty of answers here, and one's been accepted, but IMO they all make it harder than it needs to be. I think the following is simpler and cleaner:
static string NextColumn(string column){
char[] c = column.ToCharArray();
for(int i = c.Length - 1; i >= 0; i--){
if(char.ToUpper(c[i]++) < 'Z')
break;
c[i] -= (char)26;
if(i == 0)
return "A" + new string(c);
}
return new string(c);
}
Note that this doesn't do any input validation. If you don't trust your callers, you should add an IsNullOrEmpty check at the beginning, and a c[i] >= 'A' && c[i] <= 'Z' || c[i] >= 'a' && c[i] <= 'z' check at the top of the loop. Or just leave it be and let it be GIGO.
You may also find use for these companion functions:
static string GetColumnName(int index){
StringBuilder txt = new StringBuilder();
txt.Append((char)('A' + index % 26));
//txt.Append((char)('A' + --index % 26));
while((index /= 26) > 0)
txt.Insert(0, (char)('A' + --index % 26));
return txt.ToString();
}
static int GetColumnIndex(string name){
int rtn = 0;
foreach(char c in name)
rtn = rtn * 26 + (char.ToUpper(c) - '#');
return rtn - 1;
//return rtn;
}
These two functions are zero-based. That is, "A" = 0, "Z" = 25, "AA" = 26, etc. To make them one-based (like Excel's COM interface), remove the line above the commented line in each function, and uncomment those lines.
As with the NextColumn function, these functions don't validate their inputs. Both with give you garbage if that's what they get.
Here’s what I came up with.
/// <summary>
/// Return an incremented alphabtical string
/// </summary>
/// <param name="letter">The string to be incremented</param>
/// <returns>the incremented string</returns>
public static string NextLetter(string letter)
{
const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (!string.IsNullOrEmpty(letter))
{
char lastLetterInString = letter[letter.Length - 1];
// if the last letter in the string is the last letter of the alphabet
if (alphabet.IndexOf(lastLetterInString) == alphabet.Length - 1)
{
//replace the last letter in the string with the first leter of the alphbat and get the next letter for the rest of the string
return NextLetter(letter.Substring(0, letter.Length - 1)) + alphabet[0];
}
else
{
// replace the last letter in the string with the proceeding letter of the alphabet
return letter.Remove(letter.Length-1).Insert(letter.Length-1, (alphabet[alphabet.IndexOf(letter[letter.Length-1])+1]).ToString() );
}
}
//return the first letter of the alphabet
return alphabet[0].ToString();
}
just curious , why not just
private string alphRecursive(int c) {
var alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
if (c >= alphabet.Length) {
return alphRecursive(c/alphabet.Length) + alphabet[c%alphabet.Length];
} else {
return "" + alphabet[c%alphabet.Length];
}
}
This is like displaying an int, only using base 26 in stead of base 10. Try the following algorithm to find the nth entry of the array
q = n div 26;
r = n mod 26;
s = '';
while (q > 0 || r > 0) {
s = alphabet[r] + s;
q = q div 26;
r = q mod 26;
}
Of course, if you want the first n entries, this is not the most efficient solution. In this case, try something like daniel's solution.
I gave this a go and came up with this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Alphabetty
{
class Program
{
const string alphabet = "abcdefghijklmnopqrstuvwxyz";
static int cursor = 0;
static int prefixCursor;
static string prefix = string.Empty;
static bool done = false;
static void Main(string[] args)
{
string s = string.Empty;
while (s != "Done")
{
s = GetNextString();
Console.WriteLine(s);
}
Console.ReadKey();
}
static string GetNextString()
{
if (done) return "Done";
char? nextLetter = GetNextLetter(ref cursor);
if (nextLetter == null)
{
char? nextPrefixLetter = GetNextLetter(ref prefixCursor);
if(nextPrefixLetter == null)
{
done = true;
return "Done";
}
prefix = nextPrefixLetter.Value.ToString();
nextLetter = GetNextLetter(ref cursor);
}
return prefix + nextLetter;
}
static char? GetNextLetter(ref int letterCursor)
{
if (letterCursor == alphabet.Length)
{
letterCursor = 0;
return null;
}
char c = alphabet[letterCursor];
letterCursor++;
return c;
}
}
}
Here is something I had cooked up that may be similar. I was experimenting with iteration counts in order to design a numbering schema that was as small as possible, yet gave me enough uniqueness.
I knew that each time a added an Alpha character, it would increase the possibilities 26x but I wasn't sure how many letters, numbers, or the pattern I wanted to use.
That lead me to the code below. Basically you pass it an AlphaNumber string, and every position that has a Letter, would eventually increment to "z\Z" and every position that had a Number, would eventually increment to "9".
So you can call it 1 of two ways..
//This would give you the next Itteration... (H3reIsaStup4dExamplf)
string myNextValue = IncrementAlphaNumericValue("H3reIsaStup4dExample")
//Or Loop it resulting eventually as "Z9zzZzzZzzz9zZzzzzzz"
string myNextValue = "H3reIsaStup4dExample"
while (myNextValue != null)
{
myNextValue = IncrementAlphaNumericValue(myNextValue)
//And of course do something with this like write it out
}
(For me, I was doing something like "1AA000")
public string IncrementAlphaNumericValue(string Value)
{
//We only allow Characters a-b, A-Z, 0-9
if (System.Text.RegularExpressions.Regex.IsMatch(Value, "^[a-zA-Z0-9]+$") == false)
{
throw new Exception("Invalid Character: Must be a-Z or 0-9");
}
//We work with each Character so it's best to convert the string to a char array for incrementing
char[] myCharacterArray = Value.ToCharArray();
//So what we do here is step backwards through the Characters and increment the first one we can.
for (Int32 myCharIndex = myCharacterArray.Length - 1; myCharIndex >= 0; myCharIndex--)
{
//Converts the Character to it's ASCII value
Int32 myCharValue = Convert.ToInt32(myCharacterArray[myCharIndex]);
//We only Increment this Character Position, if it is not already at it's Max value (Z = 90, z = 122, 57 = 9)
if (myCharValue != 57 && myCharValue != 90 && myCharValue != 122)
{
myCharacterArray[myCharIndex]++;
//Now that we have Incremented the Character, we "reset" all the values to the right of it
for (Int32 myResetIndex = myCharIndex + 1; myResetIndex < myCharacterArray.Length; myResetIndex++)
{
myCharValue = Convert.ToInt32(myCharacterArray[myResetIndex]);
if (myCharValue >= 65 && myCharValue <= 90)
{
myCharacterArray[myResetIndex] = 'A';
}
else if (myCharValue >= 97 && myCharValue <= 122)
{
myCharacterArray[myResetIndex] = 'a';
}
else if (myCharValue >= 48 && myCharValue <= 57)
{
myCharacterArray[myResetIndex] = '0';
}
}
//Now we just return an new Value
return new string(myCharacterArray);
}
}
//If we got through the Character Loop and were not able to increment anything, we retun a NULL.
return null;
}
Here's my attempt using recursion:
public static void PrintAlphabet(string alphabet, string prefix)
{
for (int i = 0; i < alphabet.Length; i++) {
Console.WriteLine(prefix + alphabet[i].ToString());
}
if (prefix.Length < alphabet.Length - 1) {
for (int i = 0; i < alphabet.Length; i++) {
PrintAlphabet(alphabet, prefix + alphabet[i]);
}
}
}
Then simply call PrintAlphabet("abcd", "");

Categories

Resources