Hello all,
I am facing this problem . Could you please give a hint how I have to solve it?
My code so far
var twoSum = function(nums, target) {
let gain=[ ];
for (let i=0; i<nums.length; i++) {
if (nums[i]+nums[i+1]===target) {
gain.unshift(i,i+1)
console.log(nums[i],nums[i+1])
}
return console.log(gain)
}
};
twoSum([3,2,4],6)
Side note - you shouldnât be using var
at this stage in the curriculum. It is a legacy feature of JavaScript. let
and const
are preferred.
hi there, you seem to have deleted the link to the challenge just now.
Can you add it back?
Thank you for the reply, but it doesnât affect to the result
You didnât really tell us enough to help you much -
What is happening?
What do you want to happen instead?
What have you tried to fix the code?
let twoSum = function(nums, target) {
let gain=[];
for (let i=0; i<nums.length; i++) {
if (nums[i]+nums[i+1]===target) {
gain.unshift(i,i+1)
console.log(nums[i],nums[i+1])
}
return console.log(gain)
}
};
twoSum([3,2,4],6)
this is my code so far. The problem is from Leetcode
We arenât magic âcode fixitâ machines. We canât help without knowing what is supposed to happen
Aaa, sorry for not giving clear help. It is my first time asking help in the forum.
This code should show indicies of numbers that are equal to the target when they are combined.
It works if in ânumsâ I give ([2,4,8],6). It finds first two values of numbers only that are equal to 6 when they are added.
But if I give ([8,2,4], 6) it canât find it
This return statement is inside of a loop, so you will terminate the loop early.
Also note that if you return a console.log()
, then you return the return value of that function call, which is undefined
.
Do you want any pairs or adjacent pairs only?
nurik91
November 4, 2022, 4:44pm
10
Any pairs that are equal to target when they are combined
It seems like you donât have enough loops for that with your current strategy?
nurik91
November 4, 2022, 4:52pm
12
This one helped a little bit. Year, you are right. I didnât place return out of loop, also console.log is extra. But it doesnât work when I call a function with the input
twoSum([3,2,3], 6)
Right, because you are explicitly only considering adjacent entries with your code above.
nurik91
November 4, 2022, 5:00pm
14
I see. I will try to figure out for some time. Thanks a lot
Congrats! If you are interested in bonus points - can you research and implement the one loop solution?
nurik91
November 4, 2022, 5:11pm
17
Thank you for your help. Yeah, sure.
nurik91
November 4, 2022, 5:13pm
18
Sorry another question. I have to always use console.log in VSC in order to see my results, wihout it doesnât show anything
Right, I would expect that. Nothing gets âprintâ/"log"ed unless you explicitly ask for that.
nurik91
November 4, 2022, 5:17pm
20
What I donât understand is that in python If I am not mistaken when you use return it gvies the answer in the terminal, but with JS it doesnât work in my VSC. Maybe I have some problems in the settings of the VSC