Forum Discussion
jareyesdev
Jan 24, 2024Copper Contributor
Help creating algorithm C#
Greetings, I am trying to make an algorithm that generates codes with sequential letters and numbers, the letters for example should not be repeated, example: I have these words that the codes shoul...
brandonh-msft
Microsoft
Feb 07, 2024jareyesdev
Just ask Bing 😉
Sure, I can help you with that. Here’s a simple C# code snippet that generates unique codes based on the first non-repeating character from each word. It also appends a sequential number to the end of the code.
using System;
using System.Collections.Generic;
public class CodeGenerator
{
private int count = 1;
private List<string> words;
public CodeGenerator(List<string> words)
{
this.words = words;
}
public string GenerateCode()
{
string code = "";
for (int i = 0; i < words.Count; i++)
{
for (int j = 0; j < words[i].Length; j++)
{
char letter = words[i][j];
if (!code.Contains(letter.ToString(), StringComparison.OrdinalIgnoreCase))
{
code += letter;
break;
}
}
}
return code.ToUpper() + (count++).ToString("D6");
}
}
public class Program
{
public static void Main()
{
List<string> words = new List<string> { "Category", "SubCategory", "Brand", "Model" };
CodeGenerator generator = new CodeGenerator(words);
Console.WriteLine(generator.GenerateCode()); // CSBM000001
Console.WriteLine(generator.GenerateCode()); // AURO000002
}
}
This code creates a CodeGenerator
class that takes a list of words and generates codes based on these words. The GenerateCode
method iterates over each word and character, adding the first non-repeating character to the code. It then appends a sequential number, padded with zeros to maintain a length of 6 digits. The Main
method demonstrates how to use this class to generate codes. Please note that this code is case-insensitive and treats ‘a’ and ‘A’ as the same character. If you want it to be case-sensitive, you can remove the StringComparison.OrdinalIgnoreCase
from the Contains
method.
Please let me know if you need further assistance! 😊