Language/Dart

[Exercism] Hamming

paran21 2022. 9. 8. 16:43

https://exercism.org/tracks/dart/exercises/hamming

 

Hamming in Dart on Exercism

Can you solve Hamming in Dart? Improve your Dart skills with support from our world-class team of mentors.

exercism.org

 

두 개의 주어진 문자열을 자리마다 비교해서 값이 다른 개수를 리턴하는 문제이다.

 

문제 조건에서 둘 중 하나가 empty이거나 길이가 다르면 에러를 던지도록 되어 있어서 먼저 에러 처리를 해주고,

for문으로 각 자리를 비교해 다른 경우를 count하였다.

 

if문에서 조건은 메서드로 분리를 해주는게 가독성이 더 좋다고 생각해서, 간단한 로직이지만 별도로 분리하였다.

class Hamming {
  int distance(String strands1, String strands2) {
    if (!isSameLength(strands1, strands2) && (strands1.isEmpty || strands2.isEmpty)) {
      throw ArgumentError('no strand must be empty');
    }
    
    if (!isSameLength(strands1, strands2)) {
      throw ArgumentError('left and right strands must be of equal length');
    }
    
    int count = 0;
    for (int i = 0; i < strands1.length; i++) {
      if (strands1[i] != strands2[i]) {
        count++;
      }
    }
    return count;
  }
  
  bool isSameLength(String strands1, String strands2) => strands1.length == strands2.length;
}

'Language > Dart' 카테고리의 다른 글

[Exercism] Raindrops #String #Stringbuffer #immutual  (0) 2022.09.11
[Exercism] Gigasecond #Duration #Named parameter  (0) 2022.09.08
[Excercism] Space Age #enum  (0) 2022.09.08
[Exercism] Bob  (0) 2022.09.08
[Exercism] Word Count  (0) 2022.08.31