Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.76/75: Рейтинг темы: голосов - 75, средняя оценка - 4.76
0 / 0 / 0
Регистрация: 19.06.2015
Сообщений: 3

Генератор имен

01.02.2016, 14:39. Показов 15523. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте.Подскажите пожалуйста алгоритм для генерации имен. Если есть возможность,то подскажите пожалуйста строкой кода. Думала над использованием Case или рандомного выбора из массива.Но показалось слишком просто.Нужно что-то посерьезнее.
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
01.02.2016, 14:39
Ответы с готовыми решениями:

Имя типа или пространства имен отсутствует в пространстве имен
Подскажите решение проблемы. Целиком код:

Имя типа или пространства имен "ProtectedData" отсутствует в пространстве имен System.Security.Cryptography
Такая проблема, пытаюсь собрать проект , но дает ошибки : по идее, они должны идти в комплекте ... поискал в гугле, он он кидает...

Тип или имя пространства имен 'Windows' не существует в пространстве имен "Microsoft"
Здравствуйте! Такая проблема, не могу понять, почему проект не может обнаружить ссылку на сборку. Ошибка ::: Тип или имя пространства...

2
Администратор
Эксперт .NET
 Аватар для OwenGlendower
18237 / 14151 / 5366
Регистрация: 17.03.2014
Сообщений: 28,841
Записей в блоге: 1
02.02.2016, 11:56
Лучший ответ Сообщение было отмечено justmary31 как решение

Решение

justmary31, я как-то задавался аналогичной задачей и нашел интересную реализацию на java, которую портировал на C#.
Класс NameGenerator
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
public class NameGenerator
{
    List<string> pre = new List<string>();
    List<string> mid = new List<string>();
    List<string> sur = new List<string>();
 
    private static char[] Vowels = {'a', 'e', 'i', 'o', 'u', 'ä', 'ö', 'õ', 'ü', 'y'};
    private static char[] Consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p',    'q', 'r', 's', 't', 'v', 'w', 'x', 'y'};
    Random rnd = new Random();
    private string fileName;
 
    /**
     * Create new random name generator object. refresh() is automatically called.
     * @param fileName insert file name, where syllables are located
     * @throws IOException
     */
    public NameGenerator(string fileName)
    {
        this.fileName = fileName;
        Refresh();
    }
 
    public NameGenerator(TextReader reader)
    {
        Load(reader);
    }
 
    /**
     * Change the file. refresh() is automatically called during the process.
     * @param fileName insert the file name, where syllables are located.
     * @throws IOException
     */
    public void changeFile(string fileName)
    {
        if (fileName == null) throw new ArgumentNullException("fileName");
        this.fileName = fileName;
        Refresh();
    }
 
    /**
     * Refresh names from file. No need to call that method, if you are not changing the file during the operation of program, as this method
     * is called every time file name is changed or new NameGenerator object created.
     * @throws IOException
     */
    public void Refresh()
    {
        if (fileName == null) return;
        
        using (var reader = new StreamReader(fileName))
        {
            Load(reader);
        }
    }
    
    private void Load(TextReader reader)
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            if (line.Length > 0)
            {
                if (line[0] == '-')
                    pre.Add(line.Substring(1).ToLower());
                else if(line[0] == '+')
                    sur.Add(line.Substring(1).ToLower());
                else
                    mid.Add(line.ToLower());
            }
        }
    }
 
    private string upper(string s)
    {
        return s.Substring(0,1).ToUpper() + s.Substring(1);
    }
 
    private bool containsConsFirst(List<string> array){
        foreach (string s in array)
        {
            if (ConsonantFirst(s)) return true;
        }
        return false;
    }
 
    private bool containsVocFirst(List<string> array){
        foreach (string s in array)
        {
            if(VowelFirst(s)) return true;
        }
        return false;
    }
 
    private bool allowCons(List<string> array)
    {
        foreach(string s in array)
        {
            if (hatesPreviousVowels(s) || !hatesPreviousConsonants(s)) return true;
        }
        return false;
    }
 
    private bool allowVocs(List<string> array){
        foreach (string s in array){
            if(hatesPreviousConsonants(s) || hatesPreviousVowels(s) == false) return true;
        }
        return false;
    }
 
    private bool expectsVowel(string s){
        if(s.Substring(1).Contains("+v")) return true;
        else return false;
    }
    private bool expectsConsonant(string s){
        if(s.Substring(1).Contains("+c")) return true;
        else return false;
    }
    private bool hatesPreviousVowels(string s){
        if(s.Substring(1).Contains("-c")) return true;
        else return false;
    }
    private bool hatesPreviousConsonants(string s){
        if(s.Substring(1).Contains("-v")) return true;
        else return false;
    }
 
    private string PureSyl(string s){
        s = s.Trim();
        if(s[0] == '+' || s[0] == '-') s = s.Substring(1);
        return s.Split(' ')[0];
    }
 
    private bool VowelFirst(string s)
    {
        return Vowels.Contains(char.ToLower(s[0]));
    }
 
    private bool ConsonantFirst(string s)
    {
        return Consonants.Contains(char.ToLower(s[0]));
    }
 
    private bool VowelLast(string s)
    {
        return Vowels.Contains(char.ToLower(s[s.Length-1]));
    }
 
    private bool ConsonantLast(string s){
        return Consonants.Contains(char.ToLower(s[s.Length-1]));
    }
 
 
    /**
     * Compose a new name.
     * @param syls The number of syllables used in name.
     * @return Returns composed name as a string
     * @throws ApplicationException when logical mistakes are detected inside chosen file, and program is unable to complete the name.
     */
    public string Compose(int syls)
    {
        if(syls > 2 && mid.Count == 0) throw new ApplicationException("You are trying to create a name with more than 3 parts, which requires middle parts, which you have none in the file "+fileName+". You should add some. Every word, which doesn't have + or - for a prefix is counted as a middle part.");
        if(pre.Count == 0) throw new ApplicationException("You have no prefixes to start creating a name. add some and use "-" prefix, to identify it as a prefix for a name. (example: -asd)");
        if(sur.Count == 0) throw new ApplicationException("You have no suffixes to end a name. add some and use "+" prefix, to identify it as a suffix for a name. (example: +asd)");
        if(syls < 1) throw new ApplicationException("compose(int syls) can't have less than 1 syllable");
        int expecting = 0; // 1 for Vowel, 2 for consonant
        int last = 0; // 1 for Vowel, 2 for consonant
        string name;
        int a = (int)(rnd.NextDouble() * pre.Count);
 
        if(VowelLast(PureSyl(pre[a]))) last = 1;
        else last = 2;
 
        if(syls > 2){
            if(expectsVowel(pre[a])){
                expecting = 1;
                if(containsVocFirst(mid) == false) throw new ApplicationException("Expecting "middle" part starting with Vowel, " +
                        "but there is none. You should add one, or remove requirement for one.. ");
            }
            if(expectsConsonant(pre[a])){
                expecting = 2;
                if(containsConsFirst(mid) == false) throw new ApplicationException("Expecting "middle" part starting with consonant, " +
                "but there is none. You should add one, or remove requirement for one.. ");
            }
        }
        else{
            if(expectsVowel(pre[a])){
                expecting = 1;
                if(containsVocFirst(sur) == false) throw new ApplicationException("Expecting "suffix" part starting with Vowel, " +
                        "but there is none. You should add one, or remove requirement for one.. ");
            }
            if(expectsConsonant(pre[a])){
                expecting = 2;
                if(containsConsFirst(sur) == false) throw new ApplicationException("Expecting "suffix" part starting with consonant, " +
                "but there is none. You should add one, or remove requirement for one.. ");
            }
        }
        if(VowelLast(PureSyl(pre[a])) && allowVocs(mid) == false) throw new ApplicationException("Expecting "middle" part that allows last character of prefix to be a Vowel, " +
        "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : ""+pre[a]+"", which" +
        "means there should be a part available, that has "-v" requirement or no requirements for previous syllables at all.");
 
        if(ConsonantLast(PureSyl(pre[a])) && allowCons(mid) == false) throw new ApplicationException("Expecting "middle" part that allows last character of prefix to be a consonant, " +
        "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : ""+pre[a]+"", which" +
        "means there should be a part available, that has "-c" requirement or no requirements for previous syllables at all.");
 
        int[] b = new int[syls];
        for(int i = 0; i<b.Length-2; i++){
 
            do{
                b[i] = (int)(rnd.NextDouble() * mid.Count);
                //System.out.println("exp " +expecting+" VowelF:"+VowelFirst(mid.get(b[i]))+" syl: "+mid.get(b[i]));
            }
            while(expecting == 1 && VowelFirst(PureSyl(mid[b[i]])) == false || expecting == 2 && ConsonantFirst(PureSyl(mid[b[i]])) == false
                    || last == 1 && hatesPreviousVowels(mid[b[i]]) || last == 2 && hatesPreviousConsonants(mid[b[i]]));
 
            expecting = 0;
            if(expectsVowel(mid[b[i]])){
                expecting = 1;
                if(i < b.Length-3 && containsVocFirst(mid) == false) throw new ApplicationException("Expecting "middle" part starting with Vowel, " +
                        "but there is none. You should add one, or remove requirement for one.. ");
                if(i == b.Length-3 && containsVocFirst(sur) == false) throw new ApplicationException("Expecting "suffix" part starting with Vowel, " +
                "but there is none. You should add one, or remove requirement for one.. ");
            }
            if(expectsConsonant(mid[b[i]])){
                expecting = 2;
                if(i < b.Length-3 && containsConsFirst(mid) == false) throw new ApplicationException("Expecting "middle" part starting with consonant, " +
                "but there is none. You should add one, or remove requirement for one.. ");
                if(i == b.Length-3 && containsConsFirst(sur) == false) throw new ApplicationException("Expecting "suffix" part starting with consonant, " +
                "but there is none. You should add one, or remove requirement for one.. ");
            }
            if(VowelLast(PureSyl(mid[b[i]])) && allowVocs(mid) == false && syls > 3) throw new ApplicationException("Expecting "middle" part that allows last character of last syllable to be a Vowel, " +
                    "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : ""+mid[b[i]]+"", which " +
                    "means there should be a part available, that has "-v" requirement or no requirements for previous syllables at all.");
 
            if(ConsonantLast(PureSyl(mid[b[i]])) && allowCons(mid) == false && syls > 3) throw new ApplicationException("Expecting "middle" part that allows last character of last syllable to be a consonant, " +
                    "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : ""+mid[b[i]]+"", which " +
                    "means there should be a part available, that has "-c" requirement or no requirements for previous syllables at all.");
            if(i == b.Length-3){
                if(VowelLast(PureSyl(mid[b[i]])) && allowVocs(sur) == false) throw new ApplicationException("Expecting "suffix" part that allows last character of last syllable to be a Vowel, " +
                        "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : ""+mid[b[i]]+"", which " +
                        "means there should be a suffix available, that has "-v" requirement or no requirements for previous syllables at all.");
 
                if(ConsonantLast(PureSyl(mid[b[i]])) && allowCons(sur) == false) throw new ApplicationException("Expecting "suffix" part that allows last character of last syllable to be a consonant, " +
                        "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : ""+mid[b[i]]+"", which " +
                        "means there should be a suffix available, that has "-c" requirement or no requirements for previous syllables at all.");
            }
            if(VowelLast(PureSyl(mid[b[i]]))) last = 1;
            else last = 2;
        }
 
        int c;
        do{
            c = (int)(rnd.NextDouble() * sur.Count);
        }
        while(expecting == 1 && VowelFirst(PureSyl(sur[c])) == false || expecting == 2 && ConsonantFirst(PureSyl(sur[c])) == false
                || last == 1 && hatesPreviousVowels(sur[c]) || last == 2 && hatesPreviousConsonants(sur[c]));
 
        name = upper(PureSyl(pre[a].ToLower()));
        for(int i = 0; i<b.Length-2; i++){
            name += PureSyl(mid[b[i]].ToLower());
        }
        if(syls > 1)
            name += PureSyl(sur[c].ToLower());
        return name;
    }
}


Пример генерации римских имен
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
string romanNames = @"-a
-al
-au +c
-an
-ba
-be
-bi
-br +v
-da
-di
-do
-du
-e
-eu +c
-fa
bi
be
bo
bu
nul +v
gu
da
au +c -c
fri
gus
+tus
+lus
+lius
+nus
+es
+ius -c
+cus
+tor
+cio
+tin";
 
StringReader rr = new StringReader(romanNames);
NameGenerator nameGen = new NameGenerator(rr);
rr.Close();
for (int i=0; i<100; i++)
{
    Console.WriteLine(nameGen.Compose(4));
}
1
 Аватар для 1337trix
23 / 24 / 11
Регистрация: 04.12.2014
Сообщений: 422
02.02.2016, 12:12
Жестоко... Какое именно имя? если человеческие имена и тд, то лучше их брать из отдельного архива и комбинировать (имя+фамилия+отчество) и тд, иначе имя может быть что то на подобии "фырик" и тд)))
Если же имена не зависимые ни от чего и могут быть на подобии "xh5nah-2", то вот есть функция
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
        private readonly Random random = new Random();
        public string GetPass(int x)
        {
            string pass = "";
            var r = new Random();
            while (pass.Length < x)
            {
                Char c = (char)r.Next(33, 125);
                if (Char.IsLetterOrDigit(c))
                    pass += c;
            }
            return pass;
        }
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
02.02.2016, 12:12
Помогаю со студенческими работами здесь

В чем разница между подключением пространства имен в начале файла и внутри другого пространства имен?
Привет! Есть свой класс: namespace MyNamespace { public class MyClass { }

Директива using namespace может применяться только к пространствам имен; "System.Object" является типом, а не пространством имен
Что с этим делать?

Имя типа или пространства имен "My" отсутствует в пространстве имен
private void Form1_Load(object sender, EventArgs e) { if...

Ошибка CS0234 Тип или имя пространства имен "Interpor" не существует в пространстве имен "Microsoft.Office"
Выбивает &quot;Ошибка CS0234 Тип или имя пространства имен &quot;Interpor&quot; не существует в пространстве имен &quot;Microsoft.Office&quot; (возможно,...

Ошибка: Имя типа или пространства имен "office" отсутствует в пространстве имен "Microsoft"
подключил модуль Excel = Microsoft.Office.Interop.Excel; добавляю ссылку microsoft excel 11.0 Object Library если верси имеет значение...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
Фото: Daniel Greenwood
kumehtar 13.11.2025
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru