我想从一个字符串中选择字符,这些字符的索引对应于1到100之间的素数,并在数组中返回它们。例如,如果我的输入是" abcdefghijklm"该函数应返回[" c"," d"," f"," h"," l", " n"]因为" c"对应于索引2(2 =素数)," d"对应于索引3(3 =素数)等。
这是我的代码:
shared_data
答案 0 :(得分:0)
试试这个
$(document).ready(function(){
getArrayPrime('ABCDEFGHIJLM');
});
function getArrayPrime(myString){
var resultArray = [];
for(var i=0;i<myString.length;i++){
if(isPrime(i)){
resultArray.push(myString[i]);
}
}
console.info('resultArray:',resultArray);
}
function isPrime(value) {
for(var i = 2; i < value; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
}
答案 1 :(得分:0)
添加注释以改善您当前的代码。请随时提出疑问。
function primeChars (string) {
//Why string.length <= 1 it should be 0. Even string with 1 char possible.
if (string.length <= 1) {
return "empty string";
}
var primeIdx = [];
var res = [];
//Why we need to find all primeindexes instead try to find prime indexes max upto string length or if string length > 100 then upto 100.
for (var val = 0; val <= 100; val++) {
var notPrime = false;
//can run this loop upto i< val and can avoid checking of i !== val
for (var i = 2; i <= val; i++) {
if (val%i===0 && i!==val) {
notPrime = true;
}
}
//if we will run it upto string length no need to store prime indexes just get data at those index and you are done.
//res.push(string[val])
if (notPrime === false) {
primeIdx.push(val);
}
}
for (var i = 0; i < primeIdx.length; i++) {
for (var j = 0; j <string.length; j++) {
if (i === j) {
return res.push(string[j]);
}
}
}
}