当前位置: 代码迷 >> 综合 >> exercism————Hamming
  详细解决方案

exercism————Hamming

热度:38   发布时间:2023-12-13 18:11:46.0

题目:

在这里插入图片描述

解法一(for):

package exercism;public class Hamming {
    public int hammingDistance = 0;static final char[] dnaElements = {
    'G','A','C','T'};public Hamming(String DNA1, String DNA2) throws InvalidDNAException {
    if (DNA1 == null || DNA2 == null) {
    throw new IllegalArgumentException(" DNA can not be null");}if (!checkIfVaild(DNA1,DNA2)) {
    throw new InvalidDNAException("Invalid DNA Sequence ");}for (int i = 0; i <DNA1.length() ; i++) {
    if (DNA1.charAt(i) != DNA2.charAt(i)) {
    this.hammingDistance +=1;}}}boolean checkIfVaild (String DNA1, String DNA2) {
    // check the length of DNA1 and DNA2if (DNA1.length() != DNA2.length()) {
    return false;}// check if DNA1 and DN2 only contains 'G' 'A' 'C' 'T'for (int i = 0; i < DNA1.length(); i++) {
    if (!contains(DNA1.charAt(i))) {
    return false;}}for (int i = 0; i < DNA2.length(); i++) {
    if (!contains(DNA2.charAt(i))) {
    return false;}}return true;}/*** check if a char belong to {G,A,C,T}* @param c* @return*/boolean contains(char c) {
    for (int i = 0; i < dnaElements.length; i++) {
    if (dnaElements[i] == c) {
    return true;}}return false;}}
package exercism;public class InvalidDNAException extends Exception {
    public InvalidDNAException(String message) {
    super(message);}
}

解法二(IntStream):

import java.util.stream.IntStream;public class Hamming {
    public static int compute(final String sequence1, final String sequence2) {
    if (sequence1.length() != sequence2.length()) {
    throw new IllegalArgumentException("Sequences cannot have different length");}return IntStream.range(0, sequence1.length()).map(i -> sequence1.charAt(i) != sequence2.charAt(i) ? 1 : 0).sum();// 或者 filter( s -> one.charAt(s) != two.charAt(s)).count() }
}

总结:

mentor很有耐心,一共改了九次才给过哈哈,每次都会提出一些小小的建议来帮助我改进,下面就来总结下吧:

  • Always check the input before assign them or assign them as attributes
  • Check the method siginature and if the paramater is null,or will the paramater will be something unexpect
  • When should we store a variable as a atributes,is it a need to store a variable when we can’t modify them?
  • Don’t forget to initialize variable although it will automatically assign them default value,but it is more straghtforward and clear to initialize
  • When you enter in a method, you should always start by checking the inputs. It is even more important in a constructor