Machineboy空

Excercism - Resister Color : Dictionary, Array 본문

Computer/Coding Test

Excercism - Resister Color : Dictionary, Array

안녕도라 2025. 1. 22. 13:09

문제요약

레지스터의 저항값을 나타내는 코드와 색상 매칭

https://exercism.org/tracks/csharp/exercises/resistor-color

 

Resistor Color in C# on Exercism

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

exercism.org


난이도

Easy


풀이 포인트

  • Dictionary
  • Array

REVIEW

 

우선 색상과 숫자 간의 쌍을 나타내니, 딕셔너리를 써야겠다고 생각했다.

C#으로 딕셔너리를 어떻게 선언하고 사용하는지 또 무지해서 헤맸다.

그런데 모범 답안을 보니, 색상에 해당하는 숫자값이 단순히 0부터 차례로 할당되는 방식이라

따로 자료 구조를 할당하지 않고 배열의 인덱스로 string값에 접근하는 방법으로 풀었더라.

 

숫자값이 불규칙하거나 좀 다양한 값으로 확장된다면, 딕셔너리를 활용하는 것이 좋겠다만

빠르게 풀어내기 위해 좀 더 단순하게 접근하는 법도 배워야겠다!


CODE

// 딕셔너리 방법
using System;
using System.Collections.Generic;
using System.Linq;	// 마지막 ToArray()사용하기 위함, 공부해야함

public static class ResistorColor
{
    // Color dictionary
    private static Dictionary<string, int> colorDic = new Dictionary<string, int>
    {
        { "black", 0 },
        { "brown", 1 },
        { "red", 2 },
        { "orange", 3 },
        { "yellow", 4 },
        { "green", 5 },
        { "blue", 6 },
        { "violet", 7 },
        { "grey", 8 },
        { "white", 9 }
    };

    // Returns the numeric value for a given color
    public static int ColorCode(string color)
    {
        foreach (var pair in colorDic)
        {
            if (pair.Key == color)
            {
                return pair.Value;
            }
        }
        throw new ArgumentException($"Invalid color: {color}");
    }

    // Returns all colors as an array
    public static string[] Colors()
    {
        return colorDic.Keys.ToArray();
    }
}
// Array index 활용하는 방법

using System;

public static class ResistorColor
{
    public static int ColorCode(string color) => Array.IndexOf(Colors(), color);

    public static string[] Colors() => new[] {"black","brown","red","orange","yellow","green","blue","violet","grey","white"};
}