Jan 24 2024 12:21 PM
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 should be generated based on:
Category, SubCategory, Brand, Model
First code generated: Category, SubCategory, Brand, Model
CSBM000001
Second generated code should not duplicate the words CSMM in this case it should take the second letter of each word: Category, SubCategory, Brand, Model
AURO000002
And so with the others that are generated.
Feb 07 2024 10:51 AM
@jareyesdev
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! :smiling_face_with_smiling_eyes: