Haga que la función ArrayChallenge(arr) tome la matriz de enteros almacenados en arr y determine si dos números (excluyendo el primer elemento) en la matriz pueden sumar el primer elemento de la matriz. Por ejemplo: si arr es [7, 3, 5, 2, -4, 8, 11], entonces en realidad hay dos pares que suman el número 7: [5, 2] y [-4, 11]. Su programa debe devolver todos los pares, con los números separados por una coma, en el orden en que aparece el primer número en la matriz. Los pares deben estar separados por un espacio. Entonces, para el ejemplo anterior, su programa devolvería: 5,2 -4,11
Si no hay dos números que sumen el primer elemento de la matriz, devuelva -1
Input: [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7] Output: 6,11 10,7 15,2 Final Output: --6--,--1----1-- --1--0,7 --1----5--,2 Input: [7, 6, 4, 1, 7, -2, 3, 12] Output: 6,1 4,3 Final Output: --6--,--1-- 4,3Mi acercamiento
function ArrayChallenge(arr) { var sum = [] for (var i = 0; i < arr.length; i++){ for (var j = i + 1; j < arr.length; j++){ if(arr.[i] + arr[j]=== ) } } // code goes here return arr; } // keep this function call here console.log(ArrayChallenge(readline()));¿Puedes ayudarme con esto?
Lógica
Código de trabajo
const input = [17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7]; const input2 = [7, 6, 4, 1, 7, -2, 3, 12]; const input3 = [37, 6, 4, 1, 7, -2, 3, 12]; function ArrayChallenge(arr) { var sum = [] for (var i = 1; i < arr.length; i++) { for (var j = i + 1; j < arr.length; j++) { if (arr[i] + arr[j] === arr[0]) { sum.push([arr[i], arr[j]].join()); } } } return sum.length > 0 ? sum.join(" ") : -1; } console.log(ArrayChallenge(input)); console.log(ArrayChallenge(input2)); console.log(ArrayChallenge(input3));Puede usar un reductor seguido de un bucle forEach para empujar los pares a una matriz vacía y luego unirlos al final.
const ArrayChallenge = (nums) => { const pairs = [] // Get the first and remove it from the array const first = nums.splice(0, 1)[0] nums.reduce((all, curr) => { all.forEach((a) => { // Check if we have a match if (curr + a === first) { // check if it's already in the array // we don't want duplicates if (pairs.indexOf(`${a},${curr}`) === -1 && pairs.indexOf(`${curr},${a}`) === -1) { // push the pair to the array separated by a space pairs.push(`${curr},${a}`) } } }) return all }, nums) // we pass in nums as the starting point // If there are no pairs then return -1 if (pairs.length === 0) { return -1 } else { // Join the pairs together with a space const result = pairs.join(' ') // Replace each digit (\d) with hyphens before and after const parsed = result.replace(/(\d)/g, '--$1--') return parsed } } const result1 = ArrayChallenge([17, 4, 5, 6, 10, 11, 4, -3, -5, 3, 15, 2, 7]) console.log(result1) const result2 = ArrayChallenge([7, 6, 4, 1, 7, -2, 3, 12]) console.log(result2)Su enfoque utiliza una complejidad de nivel O (n ^ 2). Esto se puede resolver usando O (n) si está dispuesto, así que sacrifique un poco la complejidad del espacio.
Lo que puedes hacer es:
Una desventaja de este método es que encontrará entradas duplicadas en el resultado. Este enfoque utiliza la complejidad del tiempo O(n) y la complejidad del espacio O(n)
function ArrayChallange(arr) { let numObj = {} let i = 1 let result = [] let tempVal // Pushing all elements of arr (from index 1) inside numObj while(i<arr.length){ numObj[arr[i]] = true } i = 1 // Looping the array to find pairs while(i < arr.length){ tempVal = numObj[Math.abs(arr[0] - arr[i])] if(tempVal){ result.push(arr[i].toString() +","+tempVal.toString()) } } if(result.length !== 0) return result.join(" ") else return -1 }