[英]initializing an array based on the values in another array in java
what's wrong with this code? 此代码有什么问题? I want to insert in array cnew as- if carr contains 'a' cnew should get 100(int), for 't'- cnew should get 101(int), for 'g'-110 and for 'c'-111.
我想在数组cnew中插入as-如果carr包含'a',则cnew应该获得100(int),对于't'-cnew应该获得101(int),对于'g'-110和'c'-111。
String s="atgc";
len=s.length();
char[] carr=s.toCharArray();
char[] cnew = new char[len];
for(int i=0;i<len;i++){
for(int j=0;j<len;j++){
if(carr[j]=='a'){
cnew[i]=100;
}else if(carr[j]=='t'){
cnew[i]=101;
}else if(carr[j]=='g'){
cnew[i]=110;
}else
cnew[i]=111;
}
}
There's no need for a nested loop : 不需要嵌套循环:
String s="atgc";
int len=s.length();
char[] carr = s.toCharArray();
int[] cnew = new int[len];
for(int i=0;i<len;i++) {
if (carr[i]=='a'){
cnew[i]=100;
} else if(carr[i]=='t') {
cnew[i]=101;
} else if(carr[i]=='g') {
cnew[i]=110;
} else {
cnew[i]=111;
}
}
Produces the following array : 产生以下数组:
[100, 101, 110, 111]
If you want cnew
to contain int
values, make it an int
array. 如果要让
cnew
包含int
值,请将其设置为int
数组。
There is no need to nested loop, because of it you are doing same operation twice. 不需要嵌套循环,因为它使您执行两次相同的操作。 Both arrays are same length, so they could use one index.
两个数组的长度相同,因此它们可以使用一个索引。
I could also propose shorter version, with Map: 我还可以使用Map提出较短的版本:
String s="atgc";
char[] carr=s.toCharArray();
char[] cnew = new char[carr.length];
Map<Character, Integer> mapping = new HashMap<Character, Integer>();
mapping.put('t',101);
mapping.put('a',100);
mapping.put('g',110);// this solution would be better for more letter mappings
for(int i=0;i<len;i++){
if(mapping.containsKey(carr[i])) {
cnew[i]=mapping.get(carr[i]);
} else {
cnew[i]=111;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.