7 kyu
Sum of two lowest positive integers
100,913 of 235,958emporio
Loading description...
Arrays
Fundamentals
View
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Spoiler
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}
-
-
Your rendered github-flavored markdown will appear here.
-
Label this discussion...
-
No Label
Keep the comment unlabeled if none of the below applies.
-
Issue
Use the issue label when reporting problems with the kata.
Be sure to explain the problem clearly and include the steps to reproduce. -
Suggestion
Use the suggestion label if you have feedback on how this kata can be improved.
-
Question
Use the question label if you have questions and/or need help solving the kata.
Don't forget to mention the language you're using, and mark as having spoiler if you include your solution.
-
No Label
- Cancel
Commenting is not allowed on this discussion
You cannot view this solution
There is no solution to show
Please sign in or sign up to leave a comment.
This comment has been hidden.
This comment has been hidden.
very easy but fun kata
This comment has been hidden.
This comment has been hidden.
Print the input to help you debug your code, but your problem is about how you set the initial value of small2. Read this, please: https://docs.codewars.com/training/troubleshooting
Similar issue observed if I retried again: here two smallest integers are 10 and 28
Thanks
First array:
5 + 5 = 10
Second array:
10 + 10 = 20
This comment has been hidden.
Thanks for your response, I had overlooked that part.
I will change my logic, Thanks
This comment has been hidden.
python fork to address poor quality test cases (which affects ALL languages, but I'm fixing python at least)
for example, as I post this, the two latest solutions are both wrong: a, b - it's kind of silly how the tests are failing to catch very common problems, and it lets down solvers that are genuinely solving it themselves instead of trivializing it with built-in functionality
my fork generates reasonably exhaustive tests (instead of randint) for lengths 4 and 5 which will catch close to all unintentionally incorrect solutions.
also js
This test was really well done. Gave me a good mental workout and really made me have to think about how to get the logic to work.
Haskell translation
Approved by Johan
so ez
The descrition mentions arrays of at least 4 numbers, in reality arrays of length 0 and 1 are passed. this is evident by the out of bound erros when accessing the elements.
the description should be updated
Fixed in Java, Crystal, and R. If there are any other languages that generate tests with less than 4 numbers, let me know.
Wrong Information within the Description "given an array of minimum 4 positive integers.". In Java tested arrays can be smaller than 4 and the integers can be negative.
Fixed the Java tests so they no longer generate incorrect ones.
JS not up to date??
what is the problem?
This comment has been hidden.
This comment has been hidden.
Rust translation
Approved by someone
Java Translation for review
Thanks to the author for his work.
https://www.codewars.com/kata/558fc85d8fd1938afb000014/discuss/javascript#66a125a0d9b42a57468382bf
This comment has been hidden.
There are no problems with the correctness of the solution. There are some comments about speed. Your solution gives a solution time of O(log(n)). And you can achieve O(n) time.
This comment has been hidden.
This comment has been hidden.
Your solution has a bug, it uses uninitialized variables.
Bugs in your solution are not a kata issue.
This comment has been hidden.
This comment has been hidden.
OP solved it, closing
Hi, I'm new here. what do you mean "OP solved it"..?
Ejini meant that the original poster (you) already solved it, so question was closed.
The problem is that you haven't solved it yet (I checked your completed katas), so he must've made a mistake...
It is difficult to tell what the problem with your code is, because it's unreadable (unformatted). You should post your code as shown here: https://docs.codewars.com/references/markdown/#code-block
It may also be helpful to print the input to console and try to debug the problem yourself. Example in Python: https://docs.codewars.com/training/troubleshooting/#print-input
@B1ts check again XD
please format it in a proper way so that other people will look at the code...
Possibly to use sort function is not good choice, it uses quick sort algorithm, but posiibly it would be quicker to make for loop twice and find min then quick sort, what do you think about that ? I ve done in both ways , but time is the same
There seems to be some data type issue with the C++ version of this kata. Extended test no. 3 returned -9223372034854775809 despite me making all in-function variables long.
i used int_64 and this eror still appear
Why didn't the Array.Sort() method work for me? I had to manually write bubble sort.
with sort, did you also use the comparison function?
I read the questions as "The lowest two even numbers" and not "positives". so my program was twice as long eliminating all odd numbers for a while. silly me.
This comment has been hidden.
This comment has been hidden.
Don't post solutions in discourse. This is not a suggestion (=suggestion of improvement of the kata). Solutions mut be submitted in the trainer and nothing more.
So, i just've checked the error in c++ compiler. num[ind1] = 508263351; num[ind2] = 1665048409; num[ind1] + num[ind2] = -2121655536; Integer overflow, means test is unsolvable. Better using smaller numbers to check programm in work.
508263351 + 1665048409 overflows to -2121655536 if you're using
int
but the kata requires you to return a
long
, where508263351 + 1665048409 == 2173311760, and does not overflow
the test is solvable in C++, and to date almost 8K coders have done so.
But in my case the same mistake appears here, even with long it returns negative number, which is unluckely to be the mistake in algorythm.
This comment has been hidden.
Seems like a solution issue, and please also remember to use the
spoiler
flag.Also,
issue
flag is for reporting kata issues, not solution issues.For information regarding your solution problem, I suggest looking into Integer Overflow, and taking a closer look at the program arguments (specifically the datatype the vector holds).
same as raised above. not a kata issue
This comment has been hidden.
you need to use the spoiler flag when discussing solution code / methods. I have added the flag to your comment
This comment has been hidden.
kata hint != kata suggestion
I'm having problems with the random tests for example Test for: 155573519, 1993171998, 12488410, 1919880710, 1973076800, 233208974, 1320911102, 448330037, 1321335736, 231848004, 1271191949, 233810757, 1166452008, 230800493, 754995815, 325133560
Expected: equal to 168061929
so i find the two minimum value are 12488410 and 230800493 that the sum is 243288903
so I guess the kata is wrong?
In what language?
c++
same as raised above. not a kata issue
This comment has been hidden.
My code passes all the tests, I keep getting this buffer error where it says that it's reached the max, so I can't submit. What should I do?
Remove your print line.
Thanks, it worked
This kata is a subject to deduplication process here: https://github.com/codewars/content-issues/issues/176.
Please join the discussion to help us identify duplicate kata and retire them.
This comment has been hidden.
This violates the original requirement of the kata in which inputs only having positive numbers (it is also written clearly in kata title)
This comment has been hidden.
Did you modify the test array numbers but forget to change the test assertion to assert 154?
This comment has been hidden.
Your current code works, not a kata issue:
Please read this: https://docs.codewars.com/training/troubleshooting
Probably you messed up the sample tests, click reset and try again.
I think the test case should also test if the original array has been altered or not. Saw someone saying that it's not a best practice to alter the array directly and the highest vote for best practice did altered the original array.
I'm not sure I'd put much sway by the "best practice" votes. I see plenty of examples of things marked as "best practice" that I'd mark as a major fail in a code review
This comment has been hidden.
This comment has been hidden.
In Python the outpout always show this:
Traceback (most recent call last): File "/workspace/default/tests.py", line 2, in from solution import sum_two_smallest_numbers ImportError: cannot import name 'sum_two_smallest_numbers' from 'solution' (/workspace/default/solution.py)
This is because you have renamed the function that the Codewars tests are expecting - the kata, when you first open the Codewars IDE, asks you to complete the function:
but instead you have renamed this function to:
better_than_average(numbers)
.So just rename your function to
sum_two_smallest_numbers
and it will solve the error.This comment has been hidden.
You forgot
using System;
, not a kata issue.What mean "should finally work for random tests"? elem (what take our function) can be not array?
The input is always an array, but in those tests the numbers inside it are generated randomly.
If it
s work with diferent numbers in array, why it can
t work with random numbers?Hi and welcome to Codewars - when you press "Test" your code is checked against a small number of fixed tests (the same for all users).
When you press "Attempt" your code is checked against many randomly-generated values/tests - this is to prevent people from hard-coding their solution, but also because it may generate edge cases that you have not considered in your code.
In this case, without further information, we don't know why your code is not working -- for example, it could be that your code is inefficient, in which case it is timing out on random tests? Or is it failing for specific input values?
Add
console.log(numbers);
to your code to see the input of the tests your code fails. Also:You don't need to check for that, it's guaranteed your function will only get positive integers.
This comment has been hidden.
That function adds two numbers, the ones you pass as
a
andb
. Now you need to figure out, how, given an array of numbers, you add the two lowest numbers of it. Find the two lowest numbers of the array, use that other function, or its code, to add them.D translation
This comment has been hidden.
Approved!
There is missing test at least for C++ that includes {INT_MAX, INT_MAX, INT_MAX, INT_MAX} Its exotic case but possible and curretly code that overflows to -2 is passing
Update to Scala 3
.
The tests keep throwing an error. Script works fine in VSCode and and repl.it with all provided test cases. STDERR: Traceback (most recent call last): File "/workspace/default/tests.py", line 2, in from solution import sum_two_smallest_numbers ImportError: cannot import name 'sum_two_smallest_numbers' from 'solution' (/workspace/default/solution.py) That is the error. Says "cannot import name"
That's because you changed the function's name, it should be
sum_two_smallest_numbers
. Not a kata issue.In JS & possibly other languages, array length should not be fixed to 5
Crystal translation available. Please check and approve.
Approved!
R translation available. Please check and approve.
Approved!
This comment has been hidden.
Not an issue, users can choose whether to add it depending on the method used
what should be the answer for an array like this [1,1,1,2,3,5,5,5,6,6,9,9,9]?
2 or 3 ?
Just follow the description.
2
This comment has been hidden.
This comment has been hidden.
Use it properly. Read the documentation of your language. Also read this: https://docs.codewars.com/training/troubleshooting/
sort method first convert into string than it short like 1122 is less than 25 because it only compare first
use for loop and compare a digit condition:array[i]<array[i-1] note :this sort only one time solution:use while loop outside
This comment has been hidden.
That function iterates through the array, and compares two elements at a time. Those two elements are
a
andb
. Ifa - b
is negative, then we know thata
is smaller thanb
, and thereforea
should appear in the sorted array beforeb
. Ifa-b
is positive, we know thatb
must be smaller and appear in the sorted array earlier thana
. That's the basics of how it works. You could achieve the same result with something like:The custom function inside
Array.sort()
is just looking for a positive, negative, or 0 return value and it uses those to arrange the elements accordingly.amazing. thank you! it's really just that simple part, the negative integer shows which is larger. all makes sense.
There is a bug in the function call in the exercise attempt tester, I ran the code I wrote along with the correct function call and the code worked.
Could you provide more informations: language, what's the problem exactly and how you fixed it exactly?
In my solution I made a copy of the original array with spread operator so as not to alter the original array but in the solutions of others I have not seen it reflected. Is it something wrong or does it not contribute much? Thanks
It is considered a bad practice to modify the input arrays, but in the great majority of katas it won't be a problem if you do it. The rare cases where it is a problem are in general badly designed katas and should be fixed.
wonderful
Added random tests for C#
Approved.
my code works perfectly localy, but there must be a bug here on this platform because I get NaN instead of the final sum as a result to return. Fix the bugs please.
It's a bug in your code. Please read this: https://docs.codewars.com/training/troubleshooting
check datatype
Im doing this in C++ which has a integer cap of 2^31 - 1 (I believe) and the question requires me to return a integer thats over this value
for the sum variable you would have to take long data type as the return type of the function is long.
This comment has been hidden.
This comment has been hidden.
Please mark your post as having spoiler content next time. Are you returning the result? Read this: https://docs.codewars.com/training/troubleshooting
This comment has been hidden.
This comment has been hidden.
Please don't give hints like that, you're practically giving the solution. This kata is very easy, it's hardly possible to help without giving the solution. I marked your answer with a spoiler flag.
This comment has been hidden.
Don't spoil solution on the discourse page. If you want to comment your solution, you can do it on the solutions page. And anyhow use spoiler flags when posting codes or clues to a kata.
The average complexity of a good sorting algorithm is nlogn, so this solution is not good, because you can solve this problem in linear time.
This comment has been hidden.
Hey devs, I passed every test but failed the random test... why so?
We don't know, but maybe this will help: https://docs.codewars.com/training/troubleshooting#works-but-no
This comment has been hidden.
i passed all the test except the random test one idk why but in that its not selcteing the smallest ones
This comment has been hidden.
This comment has been hidden.
OP solved it, closing
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
Thanks @hobovsky!
This comment has been hidden.
This comment has been hidden.
You have some typos in those var names (you went from
min1
tom1
without a reason), but even then an error in the logic, print the input, see why it fails: https://docs.codewars.com/training/troubleshooting/#print-inputWith your first attempt, besides the var names changing, walk through your code step by step. What happens if the input array is
[4, 3, 2, 1]
?This comment has been hidden.
Print the input, it'll become evident. Read this: https://docs.codewars.com/training/troubleshooting/#print-input
I don't fully understand what should be evident. I tried again and that solution worked. I don't know why, and I'd like to know... But I guess I'm an eternal noob. Anyways, thank you. I read that article the other day, and I think I need to re read it next month to really understand what it says. I don't know much about error handling. Thank you for your time.
This comment has been hidden.
If you don't print the input when your code fails, you'll be throwing punches in the dark. That's the first step when debugging your code, identify which values make your code fail. When it fails (as it was failing random tests) you can see that. It can randomly pass too, because as BobtheLantern explained above, the condition for your code to fail is there is more than one number of the second lowest value (nobody told you numbers can't repeat in the array). I hope that answer your question.
Thank you both! Now, not only I know the problem, also I understand it. I'll work in a better solution.
This comment has been hidden.
Not a kata issue. You passed the input as several arguments in VSCode and here a single array is passed.
This comment has been hidden.
1 kyu
This comment has been hidden.
This comment has been hidden.
because
indexOf
is not an individually defined function... seems you might want this:numbers.indexOf(smallestNumber)
This comment has been hidden.
You are right away incorrectly calculating the
smallestNumber
in the//Isolating Smallest Number//
block (obviously,3
is not the smallest of[5,4,1,2,3]
). Once you fix that, look also at how you calculatesecondSmallestNumber
.There is no fixed test for two identical smallest numbers in JavaScript.
This comment has been hidden.
Fixed
This comment has been hidden.
kata hint != kata suggestion ~~
Didn't get what you said...
This isn't the place to discuss solutions. If you want to leave comments, you can leave them in solution tab - either your own solution or someone else's.
Okay.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
Please don't post solutions like that in Discourse. If you want to discuss your solution, use Solutions section.
I'm sorry, I'm new to this website, is there a way i can delete my coment ?
Sadly no, but don't worry, I've already marked it as having spoiler content. Please read this: https://github.com/codewars/codewars.com/wiki/Troubleshooting-your-solution
Thanks!
EOFError: EOF when reading a line, i don't know why am i getting this error on online compiler, the code is working fine and giving me the desired output on my intellij idea. Anyone help me out please.
Read this please: https://github.com/codewars/codewars.com/wiki/Troubleshooting-your-solution
Not a kata issue, you're probably trying to get the input with
input
instead of using the argument of the function. Closing.This comment has been hidden.
In python I managed to solve it in a one-line code.
ok
This comment has been hidden.
You can, but this solution is bad, it has unnecessary performance overhead.
:( which is a better way?
given an array of minimum 4 positive integers. But on test 6 it has an array of 3 integers[1000 , 2 ,3 ]
When posting an issue, remember mentioning the language you've talking about, maybe the problem is only with that language and not with all of them.Fixed.
Confused as to why I'm getting the following error on test 3: Expected: equal to 4000000000 Actual: 4147483647 Every other test works fine... Any ideas?
I'm getting a moduleNotFoundError — is this an issue with my code or the original test code?
Change python version to 3.8 in the dropdown above the solution editor.
@Chrono79 is it possible to disable 3.6? Or otherwise maybe check
sys.version
? I suppose most people won't run into it since 3.8 is the default (?) Seems to me like the sane thing for codewars to do would be to automatically disable 3.6 where 3.8 is the defaultThanks!
This comment has been hidden.
This comment has been hidden.
You realize that despite of the solution above being not perfect, your solution is still worse? It's even slower, performs unnecessary sorting.
This comment has been hidden.
Read that again, please.
Oh sorry, I saw now.
Something wrong with the test: numbers = {2000000000, 2000000000, 2000000000, 2000000000, 2000000000} on C tests.
That's the only one I have not passed, and it seems to me that it is not controlling properly: In my opinion, it tries to convert the result to long that is not possible because 4,000,000,000 is larger than the largest value of long data type in C language.
Here's the code you can use to check the same:
and
INT_MAX: 2147483647
, which is larger than the element of array. You must've bad management of data types in your program.Fine. I got it. I was adding elements of the array and then place the sum to result variable.
Thank you!
Can I copy the array into another array? I've done that locally on my machine and I'm getting the right answers... but when I test my code here it doesn't work. Can anyone help?
beautiful :D
This comment has been hidden.
Because you didn't import some libraries.
This comment has been hidden.
Please, don't post solutions in Discourse. You can discuss your own solution in Solutions section and even there, remember to use spoiler flag, thanks.
Sorry!
i understand this works but i dont understand what a and b are or how this works. could you please explain it to me? im still new and learning
Why test don't generate float or non-positive integers?
Because the description says so.
This comment has been hidden.
Check what you're doing in your
else if
thank you sir. i will take another look into it.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
What hapens when
n > MAX
? You overflow yourarr
when copyingnumbers
into it.Also:
qsort
, which will be much faster than your implementation of bubble sort. I am not even sure if bubble sort will meet performance requirements (but maybe it will).This comment has been hidden.
That's because how type promotions work in C.
This will not work:
long toRet = firstNumber + secondNumber
because result of addition of two ints is also an int, so addition overflows, and then such overflowed result is assigned totoRet
. Addition result is not extended tolong
until actual assignment.However, these two will work:
long toRet = (long)firstNumber + secondNumber
, andreturn (long)firstNumber + secondNumber
They work because you explicitly promote one of operands to
long
, so actual addition is performed with longs and does not overflow.Main difference is: in the first case, you work with ints and you add two ints, receiving int in the result. In two remaining cases, you cast one operand to long, the other gets implicitly promoted to long, so you perform addition on two longs.
Thanks you :D. It clarifies more things to me, to be honest... xD
This comment has been hidden.
It's not formatted: https://github.com/codewars/codewars.com/wiki/Markdown-Formatting#block-code-formatting
Thanks!
i think that in this katas need test to mutation of array?
C Translation available. Please check and approve (author is inactive).
cheers
This comment has been hidden.
Hi, if you're not sure why your code does not work, post as a
question
instead of anissue
, thanks.The first major problem I can see here is you alter the declaration from
long sumTwoSmallestNumbers_(std::vector<int> numbers)
tolong sumTwoSmallestNumbers(int One,int Two)
which will never work because the test expects to pass in an int vector to your function, not two ints. The second major problem is that you then have a following code block with no declaration whatsoever. So, I say you just start fresh and reset the kata, cout the inputs of the vector, and then figure out how you're going to return the correct sum value from them.Thanks for the help, I thought you couldn't a vector into a function.
This comment has been hidden.
Read this. Your code should return a number.
This comment has been hidden.
Not a suggestion.
This comment has been hidden.
Read this, Python code is hard to read without indentation.
Hey guys! I am quite confused with the testing of this Kata. I pass all of the sample tests, but when it comes to attempting it I will fail a different random test every time. Sometimes I'll pass 98 tests, sometimes I'll only pass 17 tests. Is there anyway to see why I am failing? Thanks!
Check if this FAQ is of any help.
Thanks!
This comment has been hidden.
This comment has been hidden.
What is your problem?
This comment has been hidden.
Not an issue. If your solution crashes, that's your problem.
Nobody can see anything.
in c++, extended test 3 exceeds the maximum for a 32 bit integer.
output is
long
Honestly tho, having no negative integers is a bad point. Having non-positive integers(including 0) will enrich the kata with more challenge, making the more fun to do it.
This exercise is great. The main thing is that, at least from what I have observed, it looks like 0 is considered to be a positive integer. So it should read, non-negative integers. Besides this the kata is quite excellent.
With my solution on final attempts with random data 3 times I can't pass. But with the fourth try its fine. So it would be better if you update test data to see it.
Can you give me input and expected value?
OP no response, closing
I would add tests with negative values, as this is described in the task. It would be interesting. And katu should be reduced to 8 kyu. Thanks.
We should not change too much kata's description. And it's impossible to change kata's rank after publishing.
Kata level should be 8 kyu instead 7 kyu
Once kata is approved and a rank is set, it can't be changed.
This comment has been hidden.
When you add two integers the result is an integer and you have an integer overflow there. Use some casting.
Yes! I inferred that after reading some other posts here. Thanks for the help!
There seems to be a discrepancy between the test cases and the description. It says the array will be of only positive integers, but one of the test cases includes a negative number, so if you write a simple solution expecting only positive ingegers it fails. I think the description or the tests need to be updated to make this consistent
Is that in Ruby?
yes, sorry I didn't specify!
I'm also having trouble with getting my code to pass the final test when I try to submit my code, even though it passes the sample tests, and these seemingly want the same results - I may be mistaken in assuming these are probably the same test cases repeated, but if not I really don't know what is going wrong!
Fixed.
This comment has been hidden.
Not a kata suggestion and don't post solutions here, it's forbidden.
This comment has been hidden.
Hi, I am sort of new to all of this, so correct me if I am wrong.
I'm a little confused about this. The question states the input will be given in the form of an array but the console says that the input is a given in the form of a list when I try to call an array function. Are they supposed to be the same thing? Because Python official documentation has like 2 seperate data types of list and arrays.
The instructions are shared among the different languages and in most languages that structure is called array. There could be a note for Python, but is that really necessary?
Thanks for your reply.
Julia translation
C++ (14) Version - There appears to be an overflow issue. Maybe the datatypes in the tester need to be improved to handle larger numbers ( long long ? ) The final tests are failing on 'ExtendedTest3'(passing all the previous sample + all other previous final tests), the Actual result is a negative number '-294967296' The function returns "Expected: equal to 4000000000 Actual: -294967296", which should be impossible since I'm simply adding the smallest two elements in the range (and the array given contains NO negative numbers. I've tried experimenting with changing the function type to 'long', 'long long int', 'unsigned long long int', etc. with no success (even tried an intermediary 'long long int' variable to store the sum before returning it.). I've also tried changing the parameter type from '' to '' without success. I keep getting a failure on the ExtendedTest3 with my actual result being a negative number.
Positive Numbers -> The instructions are vague on the array (or vector if in C++ version) of the "sum of the two lowest positive numbers given an array of minimum 4 integers". Are we to assume that all the numbers that we have been given are positive? If YES, that should be more explicitly definied in the instructions, especially for a low difficulty 7 kyu problem. Language like "You may assume that all values of the array are positive". If NO, then the Sample Tests should include negative numbers for completeness along with the final tests. Also, instructions should be updated to say "There will be at least two positive values within the array" (with test cases that match this language).
long
is 64-bit on this platform and the tests are correct. Any overflow is a problem with your solution. Description updated based on de facto test behavior and the history of kata edits.UPDATE: Both issues have been resolved! I was wrong, the tester is working properly, it was my code that faulty. I have left comments below on subsequent comments that explain why. Explanation & Code samples from both my successful and unsucessful attempts are in subsequent replies marked as spoilers. Thank you to Unnamed & Chrono79!
Instructions: Thank you for updating the instructions in regards to the input, it looks good!
Overflow Issue: I will try again using some different methods. I will report progress later to this thread. If unsuccessful, I will report my code on seperate reply and mark as spoiler to avoid giving away answer. (Note, this was done, see subsequent replies, however I found out my code was faulty. Explanations and fixes are below.)
This comment has been hidden.
Read this on how to use markdown formatting. I can confirm the overflow is a problem with your code, check what you're doing there, you need some casting.
The sum of
int
s is an int. C++17, paragraphs 8.5.6, 8.3 and 7.6: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4713.pdfUpdate: I was wrong, the tester works. After working on a similar problem, I finally understood what was happening and modified my code accordingly. It now works will all the tests and I finally got credit.
Thank you to Unnamed and Chrono79 for your patience and understanding ( and the gentle hints that you gave).
All I will say here is that in the C++ version, you have to really understand your data types. Solution will be posted in the next reply (as Spoiler).
This comment has been hidden.
Hello, I run into the same error, numbers[0] and numbers[1] are int values an explicit cast like "result+= (long)numbers[0] should solve the problem. Without explicit cast there is an overflow. Hope it helps you.
Details say that you have to find the sum of the two lowest positive numbers. 0 is neither positive nor negative number, so it must not be considered as lowest positive number. E.g. [1048, 24, 0, 37, 37] - the output should be 61, not 24.
but in competitive coding you have to consider 0 as either positive or negative.
This comment has been hidden.
Implement a class representing a Graph of German cities. can anyone write a code
Here should be demand: "Sum of two lowest non-negative integers" and not "lowest positive". It is incorrect according to tests
just to be sure... x)
This is a good one to begin with. But what are test cases?
hmmm
Consider rewording instructions or adding test cases such as
i dont know what is the purpose of assert .
Description updated (based on de facto test behavior and the history of kata edits).
It seems you forgot to check the Ruby (maybe other languages?) tests comply with the new description. Fixed Ruby.
whats about the fourth testcase
Tests with negative values are required in this problem... some mistaken tests go further (flagged as correct).
Per request for clarification, as of today the Author has thoughtfully corrected the instructions to indicate this Problem only includes positive values.
Pardon me, but I think this question, at current state, is not too clear due to cognitive dissonance from reading the kata title, the code function naming, and the instructions.
Title is "Sum of two lowest positive integers" Code function name is "sumTwoSmallestNumbers"
See the dissonance?
Please correct me if I am wrong. Let me explain one way of interpretation as below:
"Two lowest positive integers" is not "Two smallest numbers".
"Lowest positive integers", mathematically, is the set of natural numbers starting from 1 to positive infinity i.e. [1, +∞) "Two smallest numbers", is the set of numbers that is more than just integers, includes rational numbers (i.e. numbers that can be expressed in fraction form of a/b e.g. ½), irrational numbers (e.g. square root of √2), as well as all negative numbers! It means the set of possible numbers stretches from negative infinity to positive infinity (-∞, +∞).
The more confusing part is that the definition of "positive integer" is not clear. Whether it is the mathematical definition (does not include zero) or the "convenient" computer science definition flavour (unsigned integer data type == positive integer, includes zero) needs to be clarified in the instructions.
Maybe this kata has been edited a few times by different hands since publishing, and it became just a little bit incoherent. Perhaps, a little more clarification and clean up in the instructions in addition to synchronizing the function name with kata title will go a long way.
This comment has been hidden.
This comment has been hidden.
Your code fails when there are tests with 2 or more lowest numbers :)
Anyways, 'looks like you solved it'
This comment has been hidden.
What if the smallest number is not unique e.g. {1,1,1,1,1,5,6,8}? Are the two smallest numbers {1,5} or {1,1}?
I have the same question.. this kata is confused
{1,1} pair is considered as smallest number pair.
I would have found it helpful to know if we should be allowing duplicates or not in our solution.
There are no restrictions, so it's any pair of numbers.
This comment has been hidden.
Your functions should return in CW, not print their result. Maybe not a problem here, but don't mutate the input. I see you're new to CW, next time, mark your posts as having spoiler content when they do, and check how to use proper markdown.
i wrote 'print()' method for the comment perception, but in program i have tried it with 'return s'.
This comment has been hidden.
Please don't post solutions like that.
This comment has been hidden.
Because
item
is alist
, and0
is anint
.---->thanks for your more clear explaination def sum_two_smallest_numbers(*numbers):
for item in numbers:
---->from my code. when i use *numbers as argument passing. this is tuple type. so this is why code failed here
for-in returns the index directly
The tests assume that all the integers in the array are positive, what if there are some negative integer values in your array.
This comment has been hidden.
Print the inputs with
console.log(v1, v2)
.Errr, that's C#, not javascript, use
Console.WriteLine(string.Join(",", yourArray));
importingSystem
first. Think what your code does if the input array is like this one:[1, 3, 2]
0 is not technically positive. sould clarify language. Otherwise, nice kata!
This comment has been hidden.
well done!
This comment has been hidden.
Trying in C++ and it looks like there's no errors but I'm having next problem: There was an issue submitting your final solution
This comment has been hidden.
easy: you're not using the spoiler flag.
other than that:
$
-named variable???This comment has been hidden.
Your function is not returning total, it's just printing it.
It worked! Thanks @Chrono79
The number 0 is neither positive nor negative, therefore it should not be used in the sum. For example: Input: [0, 1, 2, 3] Answer expected by the checker: 1 Correct answer: 3
Scala translation ready for review.
Bumping
wrong random test:
Got: 1048,61,68,7,25 Expected: 86, instead got: 32
But 32 is right...
1000,92,2,100,90 Expected: 182, instead got: 92
...
Please try the tests again, now mutating the input won't do anything ;-)
I try - got error. I give copy of my code to another person and all tests passed - mystery
You need to refresh the page ;-)
I run this code in firefox and all test passed...mystery^2
Originally i try do it in chrome, something wrong with my chrome
Yes, it's work fine now..............
Several of the solutions posted are making assumptions that are not in the original instructions. The instructions say that you will be given an array of integers, and you want to sum the two lowest positive numbers. The solutions seem to assume that no negative integers will be in the array, and do not test to see what the lowest POSITIVE integers are. If a negative integer is put into the array, a lot of these solutions would fail.
The instructions specifically state that the two lowest positive numbers should be added, but the tests are counting 0 as a valid number. Either the instructions or the tests should be changed to match.
the random tests are broken.
I'd guess JavaScript. The tests aren't broken though; make sure you're not modifying the original input with something like
splice
,shift
orpop
.Check out this kata to get a better understanding of why.
(TLDR: The tests are working on the same array you are. If you modify it, the tests receive a different input than you did)
Code passed basic tests but failed random tests. Anyone got any ideas?
Probably that.
Same here. I even tried the code, with different values, on Repl.it and it gave me the right answer each time. Maybe a bug or something like it?
I think it is what Chrono said. I tried using the .remove method first and it passed the tests and failed the random. Then I changed to another method and managed to pass in everything.
The array wasn't modified so not sure. I'll try another method to see if it works. Definitely did not sort the array.
Ok solved it. Thanks all.
indirect type conversion
I did not change anything in my code but the result change every time that I click attempt and some times got "Execution Timed Out" . . . ? ? ?
You may be modifying the input array.
I'm not modify any input array
I'm pass now (not modify anything).
You must be modifying the array because the reference solution is correct and is called after your function.
If you want, you can write your code in a comment with a
spoiler
tag.You must be modifying the array because the reference solution is correct and is called after your function.
If you want, you can write your code in a comment with a
spoiler
tag.This comment has been hidden.
I've just tested your solution and it gives correct results every time, so idk why you said that you're failing tests.
The Execution Timeout Error occurs when when your solution is not fast enough. Your
for loop
inside afor loop
makes your algorithm very inefficient.This comment has been hidden.
Not an issue.
the tests are still broken unless 72 is smaller than 19...
Are you doing that?
Thanks! oversight on my part, tests past great now
This comment has been hidden.
Read the hint again:
You've mutated the original array, that's why the expected values changed too.
T = numbers
doesn't create a copy, T is another reference to the same array.Thanks Chrono79
This comment has been hidden.
This comment has been hidden.
You're confusing
splice
withslice
. splice mutates the array in place. So if the original mutated array is used later in a control function, the results will be different.Thank you, I tried creating a copy of the original numbers array and splicing that one instead of the numbers one but it still didn't work. Why is the original affected in this case?
Because
var arr = numbers;
doesn't make a copy,arr
is another reference to the same array, if you mutatearr
, you're mutatingnumbers
too. In your second code you did create a new array with the same values. There are other ways of creating a shallow copy likevar arr = numbers.slice();
.Ohh I see now! Thank you!
i thought it was my code but this kata is misleading and has an issue. this should be fixed asap
What's misleading and what's the issue?
i totally ignored the hint "Do not modify the original array." my fault
What if there are repeated numbers in the array? Should they be consider as seperate?
Yes.
Base test should include an instance where the lowest numbers is a duplicate. I created a solution that passed all but one random test where this was the case.
This problem is badly broken, but not incurably so. The instructions say "two smallest positive integers" but clearly the tests are written to find the sum of the two smallest non-negative integers. For people who are stumped, this may be the issue that's blocking you. To fix this problem, either fix the tests to reflect the problem statement or fix the instructions to reflect the actual test cases.
It would be easier to fix if you say which language you think is broken.
Hrm? The part that says we want "the sum of the two lowest positive numbers", like I said. Zero is not a positive integer.
Sorry, my bad. I thought you were referring to the language in the problem statement that needed fixing. The fail was in the javascript version of the problem.
There are 2 ways (at least that's what I think) to fix the tests:
This comment has been hidden.
This comment has been hidden.
I'm having troubles with this, the random test cannot be passed because it tooks the 2nd and 3rd element from the array, and I didn't changed the original array, here are some samples from the random test
Log [ 1038, 40, 62, 55, 38 ] 78 Expected: 117, instead got: 78 Log [ 1000, 27, 32, 25, 40 ] 52 Expected: 72, instead got: 52 Log [ 1067, 65, 92, 50, 96 ] 115 Expected: 188, instead got: 115 Log [ 1087, 73, 32, 31, 100 ] 63 Expected: 173, instead got: 63 Log [ 1044, 72, 22, 19, 21 ] 40 Expected: 94, instead got: 40 Log [ 1076, 26, 80, 97, 0 ] 26 Expected: 177, instead got: 26
Post your code, mark your post as having spoiler content.
This comment has been hidden.
Do a
console.log
ofnumbers
before the return line, you've mutated the input.var arrayCopy = numbers; //Copy the array, just in case
doesn't make a copy, both vars point to the same array. Try looking in the web how to make a swallow copy of an array.Or you could try creating a new array instead, or both ;)
Thank you, after correctly copied the array the kata showed no errors.
Test Results are definitely wrong. After consoling "numbers" I noticed that the expected result is obtained by summing the second and third lowest numbers of the array.
[ 1031, 25, 91, 18, 43 ] Expected: 68, instead got: 43
In this case, the result is clearly 43. This must be fixed as soon as possible.
You're probably mutating the input.
Yeah. That was the problem. It messed with the test function. I think that sentence should be highlighted in another way rather than just writing "hint" next to it.
PowerShell translation Kumited! :)
According to the description the given array might contain negative numbers. From how I understand the negative ints should be ignored.
I take that as a bonus, since it increases difficulty. Only the existing Tests dont cover that.
This comment has been hidden.
There's many duplicate entries kata out there, so this one is not gonna change anytime soon!
This kata needs random tests. It has only 5 tests with same results expected.
Reraised as issue, but most languages have random tests now
This comment has been hidden.
In Python it is possible to pass all of the tests even though your code doesn't handle the possibility of the two lowest positive integers being the same number. I think that this is misleading since the test doesn't imply in any way (as far as I can tell) that the two lowest positive numbers can't be equal to one another.I recommend adding a few test cases or updating the description if you did mean for the two lowest positive integers to not be the same number.
I have some questions:
what does None should equal 13 mean. Don't understand the error. My code works fine
Your code must be wrong, are you printing instead of returning the value? None is the value your function returns and 13 is the expected value in that message.
no. i'm using return
Paste your code here, mark your post as having spoiler content. I've solved it in Python and it worked fine for me (and for the other 6933 persons before).
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
Wrong language.
numbers.sort((a,b)=>a-b); // return is not needed if we don't write in {}
What should we return if we receive an input array with only negative numbers or only with one positive number? Or if we don't have to handle it, this should be written in the description.
Positive numbers should not contains zero. Also, negative number test case should be added.
I see what you meant, it should be stated that the input numbers can be any integer. Too late for that, and it'll render a lot of solutions invalid.
This comment has been hidden.
This comment has been hidden.
Description modified some time agooo
I just want
Hint made question harder in python. I read that as "don't mess with the array for your answer" like sorting it or anything else that might make a copy.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
Discourse section isn't for showing your solution. At least mark it as having spoiler content if you want to ask something about it.
This comment has been hidden.
Also I love how the "Preview your comment" showed it the way I formatted it (like readable codeblocks and stuff, except fullscreen doesn't show the first letter) but the Post messes this up completly. Nice work codewars~.
Edit: Furthermore I can't edit my original post anymore. Is that a 'feature' bc somebody wrote an answer?
That's your code's problem, not kata issue.
For one thing, you code fails against input such as
[1,1,3]
.Then the Test cases need some work anyway, bc I passed with my last code, which I shouldn't have if that's the main problem. But I admit, that's one thing I haven't thought about properly.
Plus it's hard to guess what's not working if there is no way to debug properly. You can't always think of everything and write an own Test Case for it, especially if you're just starting to code and have a low kyu.
I can't pass random tests, for some reason it expects NaNs. Is there anything I can do about it?
Expected: NaN, instead got: 27 Expected: NaN, instead got: 76 Expected: NaN, instead got: 136 Expected: NaN, instead got: 63 Expected: NaN, instead got: 71 Expected: NaN, instead got: 13 ...
I suppose you've mutated the input array. That messes up the tests.
Thanks for replying, Voile. You're right. I was using splice instead of slice, works now.
This comment has been hidden.
Can u help me? I pass the orher test but Expected: equal to 4000000000 Actual: -294967296 I know I code it right but I don't understand why is this happening.
You must return the sum of the lowest positive numbers, not the lowest numbers. ;)
I knew that but , aparently , i declared some stuff to be int type instead of long long , but ty anyway.
This comment has been hidden.
don't std::cout << sum the result but instead use return sum; opposed to your return 0; That's why you'll always get 'Actual: 0' because your functionw ill always return 0 in any case.