2016-03-20 2 views
0

Я пытаюсь выяснить, могу ли я получить мою функцию, чтобы определить «странный человек» в массиве, живущем внутри функции. В частности, после того, как я беру строку, преобразую ее в числа и вставляю ее в массив - я хочу, чтобы она могла проходить через выходной массив и возвращать индекс, номер которого является «нечетным человеком» (т.е. «2 2 2 2 4 6 8 1 "должен возвращать индекс 7, поскольку он является единственным нечетным числом). Тем не менее, мне трудно понять, как вернуть индекс, когда функция сталкивается с ситуациями, перечисленными ниже в коде.Невозможно сравнить два значения в массиве для javascript

function notSame(numbers){ 
    var notString = parseInt(numbers.replace(/\s+/g, ''), 10), 
    sNumber = notString.toString(), 
    output =[]; 

console.log(sNumber); 

for(var i = 0; i < sNumber.length; i+=1) { 
    output.push(+sNumber.charAt(i));  

} 

for(var num1 = 0; num1 < output.length; num1++) { 
    for(var num2 = 1; num2 < output.length; num2++) { 
    if(output[num1] % output[num2] === 1) { 
     return num1; 
     } 
    } 
    } 
} 

notSame("2 2 2 2 4 6 8 1"); /// Situation 1: should output index 7 as it is the only odd number 
notSame("5 7 9 2 1"); ///Situation 2: should output index 4 as it is the only even number 
+0

notSame ("5 7 9 2 1"); должен вернуть 3 – John

ответ

0

После того, как у вас есть целые числа в массиве output,

// test the first three array members 
    var test = Math.abs(output[0])%2 + Math.abs(output[1])%2 + Math.abs(output[2])%2; 
// if the sum of the mods of the first three integers in the 
// array is more than 1, the array is mostly odd numbers, hence 
// the odd one out will be even, else it will be odd 
    var outlierIsOdd = test >= 2 ? false : true; 
// find the odd one out and return it's index 
    return output.indexOf(output.filter(function(e){ 
    return (Math.abs(e)%2 === +outlierIsOdd); 
    })[0]); 
0

Вы могли бы найти легче сломать эту проблему на более мелкие единицы.

// return an array from a string 
function toArray(str) { return str.split(' '); } 

// return the element if it's even 
function even(el) { return el % 2 === 0; } 

// return the index of either true/false 
function getIndex(arr, flag) { return arr.indexOf(flag); } 

// count how many instances of true are in the array 
function count(arr) { 
    return arr.filter(function (el) { 
    return el; 
    }).length; 
} 

function check(str) { 

    // return an array of true/false values 
    var evens = toArray(str).map(even); 

    // if there is more than 1 true value in `evens` 
    // return the index of false from the array 
    // otherwise return the index of the only true element 
    return count(evens) > 1 ? getIndex(evens, false) : getIndex(evens, true); 
} 

check('2 2 2 2 4 6 8 1'); // 7 
check('5 7 9 2 1'); // 3 
check('2 5 2 6 6'); // 1 
check('7 7 7 9 1 3 8 1 5') // 6 

DEMO

0

function notSame(string) { 
 
    var even = []; 
 
    var odd = []; 
 
    string.split(" ").forEach(function(e, i) { 
 
    string.split(" ")[i] % 2 ? odd.push(i) : even.push(i); 
 
    }) 
 
    even > odd ? document.write(even) : document.write(odd); 
 
} 
 

 
notSame("2 2 2 2 4 6 8 1");

Заполнение 2 массивов с индексом: один за коэффициентом и один для эвенов и сравните длину.