一、题目链接
http://noi.openjudge.cn/ch0107/03/
二、解题思路
2.1 循环遍历两个给定DNA基因序列的每对碱基对:
▲ 如果当前碱基对相同,则令计数器增加1
;
2.2 根据相同碱基对的数量计算相关度,如果相关度不小于给定阈值则输出yes
,否则输出no
。
三、实施步骤
3.1 自定义方法public boolean isCorrelative(String dnaOne, String dnaTwo, double threshold)处理所有业务逻辑:
→ 参数dnaOne
为String
类型的对象,代表第一个DNA基因序列;
→ 参数dnaTwo
为String
类型的对象,代表第二个DNA基因序列;
→ 参数threshold
为double
类型的浮点数,代表给定的阈值;
→ 方法isCorrelative
返回true
当且仅当dnaOne
和dnaTwo
的相关度不小于threshold
,否则false
。
自定义方法public boolean isCorrelative(String dnaOne, String dnaTwo, double threshold)实施步骤如下:
首先,定义char[] one=dnaOne.toCharArray()
和char[] two=dnaTwo.toCharArray()
,将dnaOne
和dnaTwo
的内容转存为字符数组处理;
其次,定义int
类型的变量same = 0
,n=dnaOne.length()
,分别代表text
中数字字符的个数;
然后,通过foreach循环遍历chars
数组的每个元素e
,循环处理如下:
▲ 令ans=(isDigit(e)?ans+1:ans)
;
最后,返回ans
。
3.2 在方法main
中输入给定字符串,将其作为参数注入方法count
,输出计算结果。
四、Java程序
import java.util.Scanner;
public class Main {
/**
* 判断两个给定的DNA基因序列是否相关
*
* @param dnaOne String类型的对象,代表第一个DNA基因序列
* @param dnaTwo String类型的对象,代表第二个DNA基因序列
* @param threshold double类型的浮点数,代表给定的阈值
* @return true当且仅当dnaOne和dnaTwo的相关度不小于threshold,否则false
*/
public boolean isCorrelative(String dnaOne, String dnaTwo, double threshold) {
char[] one = dnaOne.toCharArray(); // 将dnaOne的内容转存为字符数组处理
char[] two = dnaTwo.toCharArray(); // 将dnaTwo的内容转存为字符数组处理
int same = 0; // dnaOne和dnaTwo相同碱基对的数量,初始时为0
int n = dnaOne.length(); // DNA基因序列的长度
/* 整数标记i代表每个碱基的位置,i从0开始,到n-1为止,更新步长为1 */
for (int i = 0; i < n; i++) {
same = (one[i] == two[i] ? same + 1 : same); // 如果当前碱基对相同,则令计数器增加1
}
return 1.0 * same / n >= threshold; // 相关度不小于threshold返回true,否则false
}
public static void main(String[] args) {
Main test = new Main();
Scanner input = new Scanner(System.in);
double threshold = input.nextDouble();
String dna1 = input.next();
String dna2 = input.next();
System.out.print(test.isCorrelative(dna1, dna2, threshold) ? "yes" : "no");
}
}