Computer/Coding Test

Excercism - Robot Name : Random, 중복체크, 아스키코드

안녕도라 2025. 2. 4. 12:55

문제요약

로봇 이름을 무작위로 생성하라

  • 규칙 : 대문자 2개 + 숫자 3개로 이루어지며 중복되지 않는다.
  • 예 : RX837, BC811

https://exercism.org/tracks/csharp/exercises/robot-name

 

Robot Name in C# on Exercism

Can you solve Robot Name in C#? Improve your C# skills with support from our world-class team of mentors.

exercism.org


난이도

Easy


풀이 포인트

  • 랜덤한 대문자 뽑기 : 아스키 코드(int형)에서 char 형 변환
  • 중복 체크 : Hashset 혹은 List
  • get,set 용법

REVIEW

 

아스키 코드, 예를 들어 96을 A로 만드는 방법에서 헤맸다.

그리고 중복 체크해야한다는 조건도 간과해 좀 헤매며 풀었다.

 

아직 Hashset사용법을 잘 몰라서, List로 전수 검사하는 로직을 구현했는데 좀 더 공부해 봐야겠다.

그리고 get,set도 아직 익숙하지 않은데 좀 더 연마해보기로!


CODE

using System;
using System.Collections.Generic;

public class Robot
{
	private static Random random = new Random();
    private static List<string> usedNames = new List<string>();
    
    string name;
    
    public string Name
    {
    	get
        {
        	if(string.IsNullOrEmpty(name))
            {
            	GenerateUniqueName();
            }
            return name;
        }
    }
    
    public void Reset()
    {
    	if(!string.IsNullOrEmpty(name))
        {
        	usedNames.Remove(name);
        }
        name = null;
    }
    
    private void GenerateUniqueName()
    {
    	string newName;
        
        do
        {
        	char capital1 = (char)random.Next('A','Z'+1);
            char capital2 = (char)random.Next('A','Z'+1);
            int num = random.Next(100,1000);
            
            newName = $"{capital1}{capical2}{num}";
        }while(usedNames.Contains(newName));
        
        usedNames.Add(newName);
        name = newName;
    }
}
using System;
using System.Collections.Generic;

public class Robot
{
    private static Random random = new Random();
    private static List<string> factory = new List<string>(); // 생성된 모든 이름 저장
    private string name = "";

    public string Name
    {
        get
        {
            if (string.IsNullOrEmpty(name))
            {
                GenerateUniqueName();
            }
            return name;
        }
    }

    public void Reset() {
    factory.Remove(name);  // 이전 이름 제거
    name = null;           // 초기화
    GenerateUniqueName();  // 새로운 이름 즉시 생성
}

    private void GenerateUniqueName()
    {
        bool isUnique = false;

        while (!isUnique)
        {
            char cap1 = (char)random.Next('A', 'Z' + 1);
            char cap2 = (char)random.Next('A', 'Z' + 1);
            int num = random.Next(100, 1000);

            string newName = $"{cap1}{cap2}{num}";

            if (!factory.Contains(newName))
            {
                name = newName;
                factory.Add(name);
                isUnique = true;
            }
        }
    }
}