6 kyu
Sum of Digits / Digital Root
7,926 of 288,905user578387
Loading description...
Mathematics
Algorithms
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.
I think this is too easy kata for 6 kyu
Please, approve my BF translation: https://www.codewars.com/kumite/68161784dc7f1b24812b211c?sel=68161784dc7f1b24812b211c
Rejected by someone
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
Your solution does not fail for 11. It fails for
493193
because it returns 11, instead of 2.couldn't make it simpler ;/
Java:
camelCase
, notPascalCase
Refer here on how to enable backward compatability to not invalidate all solutions
This comment has been hidden.
Remember to use
spoiler
flag when posting solutions.You can check Python solutions of other users https://www.codewars.com/kata/541c8630095125aba6000c00/solutions/python and see what are the other ways of solving the challenge. Some have simpler code, some have more complex code.
This comment has been hidden.
Your code should return the result instead of printing it. Mark your post as having spoiler content next time, please.
This comment has been hidden.
Greetings! I made the 'coolest' fork of the Kata translation to Lua. I'm not sure if I should post this here, but I followed the example of user 4500zenja1.
Approved.
Swift fork with added random tests as well (probably resolving the invisible issues below)
Merged.
Clojure fork with added random tests
Merged.
PHP fork updating the version to 8.0 via changing the test class to
DigitRootTest
approved by hobovsky, thx :)
The problem is with passing an argument with leading zeros which browsers treat as octal number. Eg. 015 is beeing converted to 13 which throws our code off. If there was some way to test whether our input have leading zeros, then in such case we might convert it to decimal eg. 015.toString('8') gives 15, so 1+5 = 6.
In many languages, leading zeros are illegal.
In most languages, it is not possible to determine the original base of the number after it is created.
This additional spec cannot be consistently implemented across all languages & will cause 276k+ solutions to be invalidated + unfair difficulty across different languages.
I think it is better to keep the current spec & just return the digital root in base 10, like in the description.
This comment has been hidden.
You got tricked by how
|
works with large numbers.This kata is broken. The test results don't match the tests. I was able to make the tests work by updating the results in assert, but in the "attempt" it failed because again, results don't match the test. Example: "expecte 2 + 8 + 8 + 4 + 0 + 0 to be 6" - wrong test data and results.
Frustrating, as it was the first kata in js.
It's not the tests that are broken, it's your solution. Maybe you misunderstood the task.
I copied your code and ran it, here's the first bit of feedback:
Your returned
15
is more than 1 digit long. You need to repeat this process until you get one-digit number (15
->1 + 5
->6
)Groovy translation
Approved
Love the Kata! :) Thanks for making it - some great solutions out there, too!
I don't understand regarding this Digital Root: what is "None should equal 7"? Very inexperienced but trying to solve from scratch and learn.
I assume your language is Python.
You should return a number from your function like this
Yeah, thanks) I figured it out when started to think:)
The naming is quite poor for this kata. DRoot as a classname is a pointless abreivation which sacrifices clarity for no gain as DigitalRoot is an acceptable class name. digital_root as a method name is worse because it bucks the Java convention of using lower camel-case for method names. Otherwise it was good and fun to solve!
Stream work, but no Kata)))
This was a fun kata! I (and most others, I expect) definitely had an "oh crap" moment when I realised that this was a RECURSIVE sum of digits - I suggest the title of the kata could be altered to better reflect this. Apart from that, it was a fun quickie to test my clojure with.
It's written in the first sentence of the description:
Javascript: Incorrect answer for n=0: expected 1 to equal +0, all combination are passing, only this one
OP solved it by handling the edge case, closing
why recursion not work 😭😭😭
Ok,I found a solution. ACCIDENTALLY
Read up on how Python's
range
function works, specifically how it handles boundaries. If you fix that issue you won't need your strange exception handling bit at the end.This comment has been hidden.
sum
is a built-in function. Check your variable names againI think that most people who try this problem are not getting from the requirements/instructions that if a final result ends up with a multiple digit number (e.g. 12, 432, 9345), then the solution needs to be performed again recursively until the result is a single digit number (e.g. 1, 0, 9). This means that 2215 is not equal to 10 since 10 is a result with more than a single digit. Then 10 will need to be processed again and the result will be 1.
This comment has been hidden.
The
Issue
label is for provable kata issues. Please use theQuestion
label when asking for help. See https://docs.codewars.com/training/troubleshooting#post-discourse.If we define "doesn't work" as throws the error
RangeError: Maximum call stack size exceeded
, then your code doesn't work because it recursively callsletsGoo
infinitely, but that isn't the only thing wrong with your code. This article might help with some of the things you're currently doing wrong: https://docs.codewars.com/training/training-example.You have already got an explanation for the error.
What I want to add, is that your function
letsGoo
will always overwrite the value of its paramter with1234
.When you firstly call
console.log(letsGoo())
, the number will be 1234. Sum will be 10, so inmain()
theelse
block will be used, which callsletsGoo(10)
.But then 10 is changed to
1234
right at the start of the function, so you end up with a recursive function that calls itself for infinite. That's why you get the Stack Overflow error, because the Call Stack can hold maximum ~10.000 calls (limited by JS engine).The second mistake is that the
sum
is initialized with 0 outside the function, and it gets bigger with everyletsGoo()
call, without reflecting the sum of the digits of the actual number during each call.It looks like this:
Also, look up on
.reduce()
method of the Array instance. Personally, I prefer using that.This comment has been hidden.
The
Issue
label is for provable kata issues. Please use theQuestion
label when asking for help. See https://docs.codewars.com/training/troubleshooting#post-discourse.Your local tests are incomplete and/or wrong. Reread the description, your code doesn't do what it needs to do.
you have to iterate until the final results has only 1 digit
Thank you Nuno and Emilio, I got it solved.
well this is'nt that bad of a function and the idea's pretty clever, however you didn't think about the case where the sum of all digits of this string ends up being superior to 10 which don't feet the instructions, supposing we have to return a 1 digit number
This comment has been hidden.
See https://docs.codewars.com/training/training-example#writing-a-solution.
Not a kata issue. See https://docs.codewars.com/training/troubleshooting#post-discourse.
Execution Timed Out in C# put smaller numbers on attempt because my solution is correct
Why are you shuffling the array elements? Your code has an infinite loop and that's why it doesn't pass the tests, even the smallest ones where the first sum is greater than 10.
9 + 3 is greater than 10 and 3 + 9 is exactly the same, addition is commutative so I don't know what you were trying to achieve with the shuffling. Improve your code, it is not correct.
hello and i am having some issues in understanding the way to return the value in javascript. i am trying to make the first condition of the recursion aka return 0 oe just say it is an invalide value and doesn't work saing that the string or just returning a n or ß is incorrect. can someone eyplain please?
Hello everyone! =)
The task is interesting and suitable for both beginners and professionals to train algorithmics.
There is a remark: The test cases clearly do not cover the main cases.
As an example, you can add: 131221 --> 1 + 3 + 1 + 2 + 2 + 1 = 10 --> 1 + 0 = 1
Thanks for the kata!
What do you mean? There are plenty of test cases such as this, including a fixed test with n = 10. Which situation exactly isn't covered?
This comment has been hidden.
Your code is incorrect. Run following test case in your VS Code and tell us what happens:
Your code performs recursion incorrectly, it is not a kata issue.
This comment has been hidden.
But what exactly is the issue here? Is there a problem that something passed, but should not? Or that something did not pass, but should?
Please remember to use code blocks when posting code.
Why the same code dosen't work in PHP ?
Without code formatting I cannot read the code, so I am not sure if both C++ and PHP code are the same. You'd need to post the code once again, using proper formatting this time, to make it readable (see the link I posted in my previous message).
This comment has been hidden.
These two pieces of code are not the same. In C++, you have a global variable, which you do not have in PHP. Additionally I think (I can;t remember exactly tho) that in PHP the
/
works differently than in C++.You already raised one issue, so could you please remove the other one? These 2 code snippets don't look the same.
/
operator returns float values in PHP, whereas it does integer division in C++.I deleted the duplicate issue.
If someone is certain that these two codes are not equivalent and PHP is correctly rejected, please mark this issue as resoved (i cannot check exactly now).
I just checked and yes, this seems to be the problem: C++ code and PHP code work differently, because
/
is integer division in C++, and not in PHP. After replacing/
withintdiv
in PHP, and making it equivalent with the C++ one, it worked.It's not a kata issue, the C++ and PHP code given above are not the same.
Thx man :)
It keeps saying "expected undefined to equal 7" why is that? but my code works right when I displays it in console?
your code returns undefined. it should return the actual value, printing to console will not pass the kata
This comment has been hidden.
Although there are better ways to implement this kata, your algorithm should also work, as long as you fix two problems.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This environment loves recursion. Recursion is the favorite treat of this environment.
Your recursion is not correct tho.
This comment has been hidden.
Well, the first mistake is not formatting the posted code ;) Please see this for help: https://docs.codewars.com/references/markdown#code-block
The one who does nothing makes no mistakes. Thank you for the literature, I will publish the code correctly in the future. Thank you :)
OP solved it, closing
mine passed the test cases, but failed with n = 0. i don't know why?
supposed to report undefined, but mine isn't desined to run with a 1 digit number.
edit: managed to get mine to pass, but it's so sloppy compared to top results.
This was fun to solve.
with input 11 my output is 2, and yet my test fails. qith input 10 my output 1 and yet my tests still fail
my function works as expected. can anyone tell me why the tests continue to fail?
Why does test 7 fail? I can't figure out what's wrong as the test case is hidden for me.
but you can easily print the input:
Touché and arigato!
Lol I don't understand any of the top solutions
This comment has been hidden.
Hi! I'm not particularly a tutor, but maybe I can help you with some tips. What kind of problems are you struggling with?
Not a kata issue. Read the docs or go to Discord
This comment has been hidden.
You're reading the error message wrongly. Your code is returning the multiple digits number, the expected answer is always a single digit number. Not a kata issue.
This comment has been hidden.
I'm using javaScript to solve the problem, Is that a problem because it's failing
what is the solution ??
@Gifftybabe ~ using JavaScript is not a problem, almost 83K solvers have successfully completed the kata in JS
@Sachin958 ~ you should not be asking for solutions, you need to solve the kata yourself
everything works in my local environment but it throws an error when appempted in the codewars env????
The
ISSUE
label is for provable kata issues. Please use theQUESTION
label when asking questions. See https://docs.codewars.com/training/troubleshooting/#post-discourse.This kata has been completed over 80000 times in Python. I can assure you that the problem is in your end.
Seeing you're new to codewars, I highly recommend reading the following article: https://docs.codewars.com/training/training-example.
This comment has been hidden.
What version of Swift do you use in your XCode? Is it possible to configure your local XCode to use Swift 5.3? Does your solution work locally for you in Swift 5.3?
Thanks for reply! My Xcode version: Apple Swift version 5.8.1 I think it must work on higner version of Swift
I tried your code in some REPLs and indeed it seems to compile fine on Swift 5.8, but not on Swift 5.3. However, it is not an issue with the kata itself, but rather with general setup of Swift on Codewars. I created this ticket as a follow-up: https://github.com/codewars/runner/issues/261, and I am going to close this discussion as not a kata issue.
This comment has been hidden.
There is no need to leave a hint in every kata.
Especially a hint with poor performance characteristics :)
Chrono79 So can I do that? I understand that there is no need, but is it restricted? Considering I give vague hints, not detailed, for general direction where to move, for new learners.
hobovsky I give any working hint I have. If people don't like the hint, they downvote my comment. After completing the task using poor performance hint, they can improve their solutions analyzing other people's solutions, therefore improving their code performance.
I wouldn't do it. If the kata's author would wanted to give a hint, it would be written in the kata's description. Even new learners should learn to search for some method by themselves or use some other things to solve the kata by themselves. And if they can't, and only then, they can ask for a hint.
Fair. Thanks 🤝
This comment has been hidden.
The
ISSUE
label is for provable kata issues. Use theQUESTION
label when asking a question. See https://docs.codewars.com/training/troubleshooting/#post-discourse.This means that your solution returned
None
when it should have returned6
. Sounds like you're printing instead of returning. See https://docs.codewars.com/training/troubleshooting#.print-vs-return.Not a kata issue.
Thank you for your response!
In file included from main.cpp:7: ./tests.cpp:5:19: error: use of undeclared identifier 'digital_root' Assert::That(digital_root(16), Equals(7));
Yes it is. You renamed the function. Change it back to that. Not a kata issue, use Question label next time.
This comment has been hidden.
Because you're doing recursion wrong. The value is lost and your function returns undefined.
Wait, how is the value lost?!
This comment has been hidden.
This comment has been hidden.
Please use appropriate formatting when posting code and the
QUESTION
label when asking a question or asking for help. TheISSUE
label is for kata issues. See https://docs.codewars.com/training/troubleshooting/#post-discourse.You're not doing what the kata is asking for, reread the description. Also, since you're a beginner, you might want to try easier kata first.
Not a kata issue.
This comment has been hidden.
This comment has been hidden.
Please don't post solutions in the discourse. Also, when posting snippets of code, use the spoiler flag and appropriate formatting. See https://docs.codewars.com/training/troubleshooting/#post-discourse.
This comment has been hidden.
No it doesn't, that returns a number of more than one digit depending on the input value. Not a kata issue.
This comment has been hidden.
Sounds like you don't even know where to start. If that's the case, you should try easier katas (e.g. 8kyu).
This comment has been hidden.
Your solution returns wrong answer for n=55.
This comment has been hidden.
And what would be the issue?
Incorrect answer for n=10: expected 10 to equal 1 Completed in 2ms Should pass random tests Incorrect answer for n=563527: expected 10 to equal 1
10
is not a single-digit number? Is it should next10 --> 1 + 0 = 1
? Is a test case error ??Yes,
10
has two digits, so you need to continue until you arrive to a single-digit value.This comment has been hidden.
Honestly not sure whats going on in C#, i've tried two solutions, while loop and recursion, both of them work correctly in my IDE, but here it either times out or gets stack overflow exception, any ideas why?
nevermind i am dumb and forgot to handle 0 ¯_(ツ)_/¯
Same issue with mine. I can get the correct outputs from my IDE but whenever I try it on this site it gives error.
This comment has been hidden.
Not a kata suggestion. Also, please don't post solutions in discourse. Read this: https://docs.codewars.com/training/troubleshooting#post-discourse
So I am having "StackOverflowError" at 7 test all the time, but its everything okay with 1 to 6 and 8th test. Dont get it, why? Whats the input?
If you mean java, it's n=0.
That`s quite smart, thank you!
I'm having issue with the random check in this kata, i tried it in another compilator and it works but it timesout when i click Attempt. I can't understand why since it seems very optimised to me
Your code times out with tests like this:
Not a kata issue.
Add
#include <stdio.h>
at the start andfflush(stdout);
after your print line to see the input that makes your code fail.Your solution has a bug and times out for example for following input:
n=1875016745ull
. It's not a kata issue.EDIT: doh, too late.
Are we supposed to use recursion? I thought the Kata suggests so but after finishing I saw loads of solutions that don't.
No, it's optional.
This comment has been hidden.
Please see this post.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
Don't post solutions like that again, please.
oky I'll remember it next time
This comment has been hidden.
such an amaizing kata. heads up, use lambda or normal function for doing the summing and check the len each time (type casting).
recursion
hi all, I am geting a UnboundLocalError and i have no clue why? :(
This comment has been hidden.
This comment has been hidden.
Things you do wrong:
The right answer for that test is indeed 4, not a kata issue.
Thanks for the like on how to post code.
But idk how i should know that it is not bugged.
Also I did debug my code locally, but i guess u know better.
That's a hint about the kata being not bugged. Then you should manually check the result:
Удобней всего решать рекурсией
tryed by recursion and by loops, both pass all test but dont pass kata, can some one explain me how can i fix hits? thx
In file included from main.cpp:6: ./solution.cpp:17:1: warning: control may reach end of non-void function [-Wreturn-type] } ^ 1 warning generated. solution.cpp:1:7: runtime error: execution reached the end of a value-returning function without returning a value
The above is the error i am getting i don't know where i am going wrong could anyone suggest me what might be causing this ??
This comment has been hidden.
This comment has been hidden.
You're doing recursion wrong.
In this particular KATA all test are ok. Even on my local machine (node 16) everything is ok, but where I click the attempt button - error (( How it is possible?
For me your solution works without problems so there is no issue with this kata. (There might be server problems currently on Codewars side which you may be affected by)
You can log inputs with
console.log(n)
to inspect what tests you are failing if any.I'm having the same issue, even testing by log works fine all the examples but when I attempt it goes stack overflow
With your current code you don't get stack overflow, but your code is wrong. Check the last lines.
This comment has been hidden.
This comment has been hidden.
that's right thanks alot :>
Didn't realise you could change the method signature. I noticed some people (using recursion) changing the return type to long to avoid the cast to int when n < 10
This comment has been hidden.
Added tests for Python.
Thanks!
How do I write to the console for debugging?
I just did a JS exercise and console.log() worked, but in C#, System.Console.WriteLine() does not work.
I don't get an error, I just don't see anything.
This comment has been hidden.
Hey @defektonfleek , welcome to Codewars and happy new year!
On Codewars you must
return
your solution rather than justprint
to console - so replaceprint(sum)
etc in your code byreturn(sum)
and try again.You can read also the beginners docs here and also this useful troubleshooting guide
Good luck on your Codewars journey!
should be a 7 kyu
Oh wow everybody, look at mr. big brain over here. I feel like at 2 kyu, you should know better than to comment stupid stuff like this.
Calm down, I was just stating my opinion. Also you made a typo in your comment, it should be "know" instead of "no". Cheers :)
This comment has been hidden.
That's a problem with your code, not a kata issue. You have an infinite loop if the initial number is a single digit number. Please read this: https://docs.codewars.com/training/troubleshooting#post-discourse
Very easy and interesting problem
I must be too stupid to do this then
same xD i know how to solve it theoretically.. guess i dont have enough experience with writing code lol^^
This comment has been hidden.
Please don't post solutions in Discourse.
I´m getting this error: RangeError: Maximum call stack size exceeded but don´t understand why. I have no more ideas how to proceed. Can someone help?
Read this: https://docs.codewars.com/training/troubleshooting/#print-input you have an inifinite recursive loop.
Infinite loop overloading their code runner, run it on your computer to help see what's making the loop
Everything works fine in my ide, that is, the result is what is expected - a single-digit number. Even tests in kata with different numbers have no problems, the logic is followed, but this is not the case in attempt. I thought maybe there is a number at the input not int, but more, but the problem is the same. I've been puzzling over this for 2 hours. Maybe kata has some verification features that I do not know about, if so, can you throw me a link to the source, please
Hi @DMG-s and welcome to Codewars;
It seems you are working in C++; I don't use that language so I can't check your solution - there are no outstanding issues though about the tests and over 9000 people have solved so it seems tests are OK and nothing wrong there.
So until a C++ user can read your comment - my best advice is to check this Troubleshooting guide for Codewars since you are new to the site.
In particular read the section about printing your inputs/outputs to console - try to see if, when you print the test inputs and your code output, can you notice which tests you are failing on?
Print the input, your code fails for numbers like this: 2106051248.
Thanks, chrono, thanks to you i could. I knew the problem was in the data types, thanks again.
In my console code works perfect. Here doesnt work and i cannot understand why. Error: expected undefined to equal 7. In my console result is equal to 7. Can explain someone this error?
Because you weren't returning the recursive call. Also, read this: https://docs.codewars.com/training/troubleshooting#expected-the-same
This comment has been hidden.
Hi @Yassinmoh - it seems you are working in JavaScript; there are 65,000 solves in that language so tests seem to be working OK.
As your error message says - you are returning the value
10
. The kata says: "...If that value has more than one digit, continue reducing in this way until a single-digit number is produced."10
has more than one digit, so your solution is not correct, you need to keep performing the algorithm one more step (probably in your code you have something likewhen n <= 10: stop loop
which should be<
instead of<=
)Thank's @benjaminzwhite problem is solved by adding = to >
Finally...
This comment has been hidden.
afaict this is a hint to the kata, not a suggestion. so i've marked it as a spoiler
This comment has been hidden.
For the 2nd sample test, your code returns
15
; notice that this is not a one-digit number.I keep getting "expecting undefined to equal 7" help please
Please make sure you are returning the result, and not just logging it to console.
I am returning the result already. still dont know what's wrong
Then you have a bug in your code. I can't tell you what's wrong without seeing it. Check your code and look for places where you're assigning to the output variable (and check the return statement). If you can't find your bug, hop on our discord and ask for help in the #help-solve channel.
The only
return
in your code is inside an if block, so if that condition isn't true, your function is returningundefined
.I keep on getting the error "expected 11 to equal 2" and I dont know why even though my code passes the test
This comment has been hidden.
"What's the problem here ???"
These tests are whack.
I am passed the testing but when i go to attempt, it says i fail 2 tests, that 10 doesnt equal 1 and 0 should equal 1. Which i dont understand at all, but I added conditions so it would and still it doesnt work.
Print the input: https://docs.codewars.com/training/troubleshooting/#print-input using
console.log()
for javascript. You have some wrong condition in your code too, why would you return 1 for 0?Currently, your solution fails with error
expected '0' to equal 0
. This means that in some situations, you return'0'
, but it should be0
.@hobovsky: Are you sure? I don't see that.
same
my code are giving this output:
4423583 --> 4 + 4 + 2 + 3 + 5 + 8 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
idk what this task want from me
i think what my visualization is not needed?
Hi, and welcome to Codewars,
Yes, your problem is that you are returning the "string" shown in the Description (really cool solution by the way!) but all the kata wants you to do is return the final result, as an
integer
.So in the above example, just rewrite your code to return
2
(aninteger
) rather than the whole string with the-->
etc.By the way, for future reference - if you are unsure about what is required for you to return in any kata, you can check the "Sample Tests" in bottom right of your screen - for example, here you will see:
test.assert_equals(digital_root(16), 7)
which means that, for input of
16
your code should return7
. That allows you to conclude that the kata wants you to return aninteger
as the result.The basic test for 12 equal to 3 is passed but random test for 12 should equal to 3, I encounter this problem.
You're misreading the error. Your function returns 12 instead of 3, but 12 isn't the input value. Print it to see what it was.
This comment has been hidden.
Read this: https://docs.codewars.com/training/troubleshooting#post-discourse
About your problem, you're doing recursion wrong, and the value is lost when it comes back because you didn't return it.
Alright thank you.
closing
Javascript: expected '0' to equal 0. -_- Wtf
I'm sure that my answer is true, all other tests have passed.
Your solution is not totally correct, for
digital_root(0)
it returns'0'
instead of0
.Ooh yeah i just solved it, Thank You.
This comment has been hidden.
Solving in C#. There is a test number -727379969. It expects 9 as the result. But the result should be 5 instead.
Thanks for this! I was getting an issue where it said my output was giving -59 when the answer should be 9 but that's impossible since my method checks for negative integers. Then I ran the test with -727379969 in my IDE and got 5!
This comment has been hidden.
That's a problem with your code, not a kata issue. Read this: https://docs.codewars.com/training/troubleshooting
Print the input and debug your code.
who solved digits root? I don't understand it! Can you explain me...
Read the description carefully and, if you don't understand a phrase or words in it , do some research. I hope that helps.
solved in rust. tests pass! but on submitting it says tests failed. also on my machine it works.
maybe it has to do with how the tests check the answers im not sure im really new.
Please read this: https://docs.codewars.com/training/troubleshooting/ and print the input to debug your code:
println!("Input value: {}", num);
Not a kata issue, it's a problem with your code.Anyone else notice how some of these parents didn't have children at the mother/daughter dance party? Who are these people and why are they hanging around little girls if they don't have children of their own??? Sorry for asking the hard questions, but somebody had to.
help this is only my second kata, using c++ but i dont get how to get each number from an int? i dont get this :c
This kata is a subject to deduplication process here: https://github.com/codewars/content-issues/issues/145.
Please join the discussion to help us identify duplicate kata and retire them.
This kata was decided to stay.
Javascript: solution to "expected undefined to equal x", you need to return your recursive function (return digitalRoot(...))
Thank you!
This comment has been hidden.
What does your solution return for n=87?
thanks, now i understand the exercise
idk why it happening my logic is all good my code returning 1 when sum is 10 but its give me a error that expected 10 equal to 1
same issue with my solutions so it must be a problem on their end
Probably the problem is on your end.
This comment has been hidden.
Don't post solutions in Discourse.
This comment has been hidden.
See the quotes around the first 0, you're returning a string instead of a number.
I solved it with map , but still find it a bit odd. In any case, thanks for the help.
This comment has been hidden.
This comment has been hidden.
Please use Spoiler flag whenever you post code, as it is visible to everyone and ruins/spoils the kata for them - I have done this for you this time.
As for your question, here's a clue to help you debug a bit more: you are missing a
return
statement somewhere in your code.final result shold be:
return(n)
or
print(n)
My test results:
Log: 2377771790541017
68
14
answer:5
Testing for n = 2377771790541017: None should equal 5
but, my return equalsTo 5 !!!
https://docs.codewars.com/training/troubleshooting/#.print-vs-return
Log
16
answer:7
None should equal 7
Log
942
15
answer:6
None should equal 6
Log
132189
24
answer:6
None should equal 6
Log
493193
29
11
answer:2
None should equal 2
'Yes, I am using return'
You're doing recursion wrong, that's why your code fails to return the result.
omg!
This comment has been hidden.
Print the input to check why your code fails, not a kata issue. Read this: https://docs.codewars.com/training/troubleshooting
I have ruined my day over this little concept actually the python is not supporting return key word at the last execution context that is why it is so hard to do it through iteration,.....
I don't understand what you are talking about, but maybe it's a good idea to learn the very basics of Python in another place and the come here to solve katas, rather than losing a lot of time without understanding what's happening. BTW that's what I have done.
thanks but if you know this katas solution, can uuh guide me
I won't, and nobody should. There are easier katas to practice on. If you can't solve a kata, don't ask for solutions, move on, and maybe someday when you have more practice you will be able so solve it easily.
ok, thanks
This comment has been hidden.
Not sure if yours is the same issue, but I experienced this problem, because my code was reducing 10 -> 10 and then kept doing that, instead of the correct 10 -> 1
what number should be return if (n<10)(for example, 5)? function should return 0 or n (5)? p.s. sorry for my english
Just apply the algorithm:
D translation
Approved!
JS: the function name should be in snakeCase.
You meant camelCase, done.
Are the test's compare the right result with n? Because the Output says "None should be equal to 6" and all my test failed, but if i print n it is 6.
You must return the result, not print it.
thank you, it works :)
This comment has been hidden.
Read this: https://docs.codewars.com/training/troubleshooting/#print-input
What happens if the number is already a single digit number?
for the testcase 444673, the sum of the individual digits is 4+4+4+6+7+3 = 28, and 8+2 = 10, then the answer should be 10, then why the testcase is expecting me to return 1?
This comment has been hidden.
1 + 0 == 1
This solution is reqeusting that you narrow it down to a single digit. So if you have 10 then you still need to reduce further to 1+0=1.
Можливо я не зрозумів суті, але чому мені видає помилку EOFError: EOF when reading a line
Hi. Please post in English (you can help yourself with an online translator if you need).
You must not use
input
here, nor call the function in your code. Just complete the code of the function. The tests call your function with different argument and check it returns the right answer.Remove this:
Also, important: you must always use the
return
instruction a the end of your function.print
has no effect (it just diplays stuff on the screen).Thank you very much, your answer helped me to understand
That was not hard
It is still unsoluble,...
I don't really get it, i used recursion with this one, It works as expected in VSCode, but not in Codewars. Does anyone have any suggestion using Javascript?
maybe share ur code so we could assess the problem. But remember to flag it as spoilers
You are doing recursion badly. It's not enough with running a recursive call, you must use its result or it's lost. I seriously doubt your program works on VSC with any number >= 10.
This comment has been hidden.
This comment has been hidden.
Answered.
same sh*t
why does the test expect 10 if it needs a single digit?
Tests never expect 10. You must misinterpret something.
expected 10 to equal 1 Never?
It means the opposite: You returned 10, it expected 1.
This means you returned 10 and should have returned 1:
Expected your answer to equal the correct answer
I understand, my English is very bad)
test code doesnt work with recurssive functions.
This comment has been hidden.
This comment has been hidden.
Please read this: https://docs.codewars.com/training/troubleshooting
You're not returning anything. The tests are fine, your code fails with numbers like this: 296588.
I figured it out later. It was a silly mistake to not return anything and just console log it Thanks for the help btw.
This comment has been hidden.
print the input
Broken Compiler my logic works everywhere else
You're doing recursion wrong, also, before saying that something is broken check this:
Explain to me how it is wrong ?
This comment has been hidden.
I forgot to return the function
i see what i did now thank you Akar!
Code works perfectly in my Repl but once I carry it over to CodeWars it says it doesn't work. Test case 11 doesn't return 2 here but it returns 2 on Repl.
Not a kata issue, your code is wrong. It's failing with
n = 905537
Ah that's great; thank you! It kept telling me test case
11 wasn't returning 2
- so I'd argue the feedback portion is unclear / broken; it should have shown905537 expected to return 2 but returned 11
.I did run 905537 in my Repl and confirmed that's what's wrong though. Back to the drawing board; appreciate the help!
there seems to be a problem in the Test Cases. There is one line that says:
Test.assertEquals( digital_root(456), 6 ) but 4+5+6 equals 15 and not 6.
@WhatInception (below) encountered the same problem apperantly.
Both of you should read carefully the description. There is no problem but in your solution.
You are right. sry!
Not working with "reduce" for javascript!
That's because your code is wrong, it's not a problem with reduce at all.
my code works perfectly on pycharm, 100 fails when i put it on here. "15 should equal 6" even though it literally does
That's a problem with your code, not a kata issue:
You're doing recursion wrong.
imma be honest my code doesnt actually work all the way but it still does put 15 as 6 in pycharm no idea why i get that many errors here
also i searched how to do recursions and man i have no idea that codes like the best i understood from it
You need to return the recursive call to your function. Your code works for 15, but it doesn't when you have to use recursion. In the error message "15 should equal 6", it doesn't mean the input value was 15, it means your function returned 15 instead of 6.
ohh ok that makes sense, ty
smth is wrong with the compiler bcause when i type my code into my own computer's compiler it works fine every time but when i type EXACTLY THE SAME CODE into the coding section in this site it returns me 31275 instead of 6
What language?
In C it seems, your code is wrong (check how you're doing your recursion), not a kata issue. Please read this: https://docs.codewars.com/training/troubleshooting
This comment has been hidden.
Print the input: https://docs.codewars.com/training/troubleshooting#print-input
Sorry but i don't have any print (console.log() in JS) the result inside the function, only return using. But I solved the problem, thanks a lot!
Printing the input you can narrow down the input values that make your code fail and debug your code easier.
C: In an external compiler/debugger, my recursive solution works with all test values - but fails test cases in codewars. Can't figure out why.
Your code not working is not a kata issue (= a bug in the kata). Please refer to the documentation: https://docs.codewars.com/training/troubleshooting
This comment has been hidden.
Because you're doing recursion wrong and when your function doesn't return you get
None
.Python:
Testing for n = 61984595376: 63 should equal 9
Why should this equal 9 and not 63?
(Also, please don't close the question unless I understand. Most people just say "idk" and close it.)
Because of that. See the examples.
Thank you very much
You're welcome.
This comment has been hidden.
There is no test with n that big. So, for the range of the input tested, it is a valid solution.
When javascript run code and console.log the same variable I am returning it shows 6 but test result I am getting states "expected undefined to equal 6"; not clear if this is an issue with the test or I am not understanding something
More than 57'000 times solved in Javascript. I think we can assume this is not a kata issue.
Thank you that was very helpful. I figured it out.
You were probably doing recursion wrong, read this: https://docs.codewars.com/training/troubleshooting
When I run the function, it seems to run one test straight after the other and only take the second returned value, and just skips the first one even though its right.
Which language? Your message is not clear at all. There is only one value to return. In different languages the tests stop as soon as a test fails and only display logs for this test.
In Js.
if I console.log(yourArgument, mySum) // [1, 6], 7 but the test seems to be testing it againt a different array to the one supplied in your argument
I'm not sure I understand your message either, but the tests are not testing against arrays but against integers:
In Javascript if I look at the sample tests I see:
Note that the input,
16
, is not an array[1,6]
. Your code therefore should work for an input of an integer.This comment has been hidden.
The test cases for creating the solution declared 6 as the answer for 456 as input (wrong -> 4+5+6=15), I fixed the text case so my solution worked. But the attemp test cases can't be modified and shows me the same error, like every answer should be 6.
You misunderstood the task, read the description again. Your code doesn't fail only with this input (though you cannot see it because random tests stop as soon as a test fails).
Thanks, and you're right. I saw the examples briefly and misunderstood the task
This comment has been hidden.
Your code not working is not a kata issue (= a bug in the kata). Also, please use markdown tags to format your code or it's not usable. Refer to the documentation about this and more: https://docs.codewars.com/training/troubleshooting/#post-discourse
This comment has been hidden.
Could it be you changed the function's name? If not, copy your code, click reset, paste it and try again.
This comment has been hidden.
Please read this: https://docs.codewars.com/training/troubleshooting#post-discourse
I didn't have time to read the posting rules))))... maybe i need another method to use to complete kata? ... this is my third kata, I have no experience yet
When you'll see easy one-line math-approach solution, you'll cry...
This comment has been hidden.
A problem with your code is not a kata issue, please read this: https://docs.codewars.com/training/troubleshooting
This comment has been hidden.
15 isn't the input, it's what your function returned. The input is 942 as in the kata's description.
Yeah thank you. I only realised after I posted the question and now I don't know how to delete this post. Thanks for the help Chono79
C language: passing tests, but when attempting I get the "Execution Time Out", and only around 10 tests passed. Using recursive function as requested, any hypothesis as why thats happening?
Hi. The description may be unclear about that, but there is no obligation to use recursion to solve this problem. However, it's possible to use recursion to solve this problem. You should try to print stuff from your code to try to catch when your code doesn't act as it should (use
printf
).for (int i = 10; i <= n; i *= 10, digits++)
if
n
is very large, there is no power of10
larger thann
that can fit insidei
, so this loops forever. for example, ifn
is2,000,000,000
, the next largest power of10
is10,000,000,000
, butINT_MAX
aka2 ** 31 - 1
is2,147,483,647
Thats great! I solved the problem turning 'i' into unsigned int. Thank you very much =)
this fixes the symptoms, not the condition. your code would still fail for very large
int
s.UINT_MAX
is just twice as large asINT_MAX
, not 10 times as large. if you want to count the number of digits of a number, you should rather divide than multiplyJavaScript: the returns of the function are always correct, as well as the data type of the return. For example, 111 returns 3, 10 returns 1, 15 returns 6, etc. Although, for some reason, only the 'Test' ends succesfully, while the 'Attempt' fails, saying that whatever number should return the other number and the return of the my function is the same as it is demanded to be, but it fails the attempt.
You are doing something wrong, because tests are ok in JS. Maybe you are misreading the log, I don't know, your message is not clear to me. I strongly advice you to read the documentation, where you can find some helpful tips: https://docs.codewars.com/training/troubleshooting/
KHINKS: your code is wrong, read troubleshooting page and print the input, see why your code fails and fix it.
This comment has been hidden.
Strange error using rust, my program logs (input, root) as 265009,22 , which is correct, but the assertion that fails is for 22->4?
Log 265009 , 22 assertion failed:
(left == right)
left:22
, right:4
This means you should return 4 but your code returns 22. Not a kata issue.
oh its supposed to be recursive
This comment has been hidden.
This comment has been hidden.
When you spent 40 minutes creating a recursive method because you saw the word "Recursive sum"... . . . .
And you saw others solved it with the math approach using 1 liner..
dude (;-;)/
This comment has been hidden.
In your
answer
variable you are making that it should doreturn answer
whereanswer
is logging (console.log
) if the length is lower than 2, just remove theconsole.log
and you're good to go.read this for yoour problem
Not a kata issue.
How to see which kind of test my script failed to pass? i can only see a backlog of error but not the initial parameters for the test
Read this: https://docs.codewars.com/training/troubleshooting/#error-messages-and-printing-your-inputoutput
Thank you!!!
This comment has been hidden.
Please stop posting solutions in the discourse. This is not a place to brag. Solutions are automatically displayed on the Solutions page.
This comment has been hidden.
You seem to misinterpret your logs and your debugging seems to be not correct. The line right after the log would return a value correctly. Your mistake is in the recursive call, which does not return what it should.
Its not a kata issue, your code is incorrect.
Thanks. Adding a 'return' statement before the recursive call fixed the issue.
I knew it would be my fault and not a Kata issue haha.
This comment has been hidden.
You can see right away from the error messages why it fails: because your code not always returns a single digit number.
How does the program want the data displayed? Print? Or is it something else? EDIT: Forgot to specify the language. Python.
You should return the result. It is the single digit number or digital root.
No random tests in C#.
Fixed. Also made the method static.
Language c#. Test integer: 80
Result:
Test Failed Expected: 9 But was: 8
But 8 + 0 = 8!
Maybe an error in the test?
There is no such test in C#.
@Tuteyshy: Think your function is recursive so what is printed includes the inputs of recursive calls. Your code has a flaw.
Thanks! I didn't notice that the Int type was overflowing.
There is a "small" issue with C# Sample Tests, inside Test() method there are two assertions which are using a "num" variable, but they are declared as instance references instead of static way (which would be "Number" instead of "num") so it is impossible to commit even a working code.
The tests work fine in C#, I'm not good at C# but my code passes correctly both random and sample tests.
I'm not any good at C# too but my code works everywhere else. Here though I get errors like "tests/Fixture.cs(23,24): error CS0176: Member 'Number.DigitalRoot(long)' cannot be accessed with an instance reference; qualify it with a type name instead", sample tests allow my code when I change it from referencing instance to doing it in a static way but those other tests can't be modified so it can't go through. Thought that it was something wrong with tests, nevermind then.
I've just tried your code. It fails on both random and sample tests raising a similar error. What do you mean
my code works everywhere else
? Why do you declare your function asstatic
? This is not the initial set up. You should respect it:By "my code works everywhere else" I meant programming environment that I tried it on and also a C# fiddle - in both cases it worked as it supposed to so that's that. And yeah, you probably found the culprit, it is static because when I was testing this function I changed it to it just for ease of testing it - so it wasn't anything purposeful, I just forgot to delete this keyword when I was copying my function here.
This comment has been hidden.
Don't post solution in Discourse, and use a spoiler flag as soon as you post somewhere possible hints to a solution.
This comment has been hidden.
Please read this paragraph of FAQ: https://docs.codewars.com/training/troubleshooting#post-discourse
Not a kata suggestion!
does anyone know what the fuck "ModuleNotFoundError: No module named 'codewars_test'" is?
Use Python 3.8. Any PU mark solve please
This comment has been hidden.
You are missing a
return
on yourelse
, since it won't return a value otherwiseThank you very much for being that extra pair of eyes! I sometimes look at some piece of code so long it just seems right to me.
No worries! We were all like that sometimes
help me!
2066 5 expected 5 to equal 9
2+0+6+6=14 => 1+4=5? why 9?
16257 3 expected 3 to equal 9
1+6+2+5+7=21 => 2+1=3 why 9?
I'm assuming you are attempting it on JS. That's weird, because I just submitted my JS code (Simple approach) and passed all the test. Edit: Oh you just passed the test
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
What is the result of
print(digital_root(56))
in your IDE?I get "None". So I'll have a little think and see if I can figure that out
Thanks once I could see what was going wrong I could find a solution.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
Please mark your post as having spoiler content next time. Both functions fail the test with 456 as input, not 16. In the second one you're adding only 4 and 5, that's why you get 9.
cheers x
This comment has been hidden.
what?
This comment has been hidden.
I added the line, "return old === undefined || old === 1 ? 7 : old" because when I test this, it tells 'expected undefined to equal 7'.
You got this all wrong.
15 isn't the argument, it's your returned value. To see the input, you can log it to console with
console.log(n)
Anyone has problem with 10 expected to be 1 ? In test the answer is true but in random I will get error!
Print the input. It's not 10, 10 is what your function returned for some other value.
This comment has been hidden.
This comment has been hidden.
Hi. Please use a spoiler flag when you post code (I put the flag for you this time), and use markdown tags to format it, or it's very discomfortable to read and, in Python particularly, it's unusable. See there: https://docs.codewars.com/training/troubleshooting/#post-discourse
This was my first comment on codewars and I tried to indent the code but failed to. I apologize for any inconvinience. Thank u
I gave you the link to format your code.
This comment has been hidden.
The function is called
digital_root
, you must keep the same name as the initial code, this is the one used by the tests to import your solution.I did use the same name and got this result: Test Results: Log 6 6 6 2 Sum of Digits / Digital Root Basic Test Cases 7 should equal 6 Test Passed Test Passed Completed in 0.02ms Completed in 0.03ms
I do need to know the where the mistake is
The code you posted with the correct function's name passes all the tests. Copy your code, click reset, paste it and try again. Maybe you messed up the sample tests somehow?
Done successfully. Thanks alot
This comment has been hidden.
Please see this bullet point: https://docs.codewars.com/training/troubleshooting#.print-vs-return
Your function is supposed to
return
the result, and not just print it.thanks a lot! I managed to complete this kata. I look at my code and other people code... it looks so bad ha ha XD. anyways thanks for help dude!
This comment has been hidden.
Please read this bullet point: https://docs.codewars.com/training/troubleshooting#.print-vs-return
It didn't help me. I tried to cast explicitly to int, str. It still doesn't pass the test. I not only display the result, but also return it
print('my value:', n) return n
Uh, it would be much easier to spot if you used proper code formatting.
Your recursive call is not correct: you ignore whatever the nested call comes up with.
This comment has been hidden.
Please don't post solution code in the discourse (or use the spoiler flag if you must). Solutions can be viewed on the solutions page by anyone interested after solving the kata.
This comment has been hidden.
This comment has been hidden.
Please mark your post as having spoiler content next time (when posting code), read this: https://docs.codewars.com/training/troubleshooting
Your code fails more than a single test, it returns wrong values, floats, for the sample tests.
This comment has been hidden.
With the code you posted, I get this:
At least in javascript, post your whole function, and mention the language you're using.
OP solved it, closing
This comment has been hidden.
This comment has been hidden.
I can not see your comment, is hidden.
I have tested my solution on local and also added the basic test here they all pass but when I run random test the test fails and says expected 10 to equal 1. When I tried to test 10 it outputs 1. I don't know why this random test is not passing while the same test passes on my local and also when I add it in basic test.
console.log the value on which your code fails, use that test data in your local to adapt your code
I have done that and it work fine on my local
No, what I mean is, your local should expect the same outcome for the given input as on Codewars, so adjust that. Otherwise your local will continue to be wrong.
Solved it. Thanks man
This comment has been hidden.
Start with printing the input to know why your code fails.
Your algorithm is incorrect. Try figuring out for which inputs you are being failed. The algorithm you are using is not inherently flawed, you're just doing it ( just a little ) wrong.
Also, please use correct indentation when posting code. Help us help you! ( and help yourself while you're at it. indentation was invented for a reason. )
Thank you for the feedback. I've never posted in the discussion before on code wars, I'm also pretty new to coding. The original code is indented but next time I'll make sure the post has the proper indentation.
This comment has been hidden.
You're doing recursion wrong in this case. Also,
console.log
prints to the console, and returnsundefined
. Return the value instead.Thanks for the response. Definitely understand about the console.log - I tried so many things and I should have stripped that out.
As for the recursion, I didn't realize Codewars looks for specific ways of getting to the final answer.
Codewars (or, to be specific, tests of this kata) do not check for a specific way of getting to the final answer. The 'you are doing recursion wrong' means simply this: your recursive call is wrong in general, and not just wrong for this kata. written this way, its not going to work anywhere, ever.
This comment has been hidden.
Read this: https://docs.codewars.com/training/troubleshooting/ you're doing recursion wrong and also don't use global vars, read why in the docs.
All the tests in my terminal with gcc are working as expected, but here I got:
Expected 6, instead got 15
That's a problem with your code, read this: https://docs.codewars.com/training/troubleshooting/ make sure you're using the same input value in both places.
Actually, something weird happened with if/else. When I used the ternary operator, the code worked real fine.
Facing a weird issue on this one, it tells me that 15 should equal 6, logical. But with a print on the input, it's not 15 that is given but 132189. So my script is actually working but the tests vs input is not correct !
15
is what your code returns, not the tested input. Not an issue.My bad, I missed a line in the description ! :/
hey everybody! maybe so can help/ has an idea! this is shown when i test ( see below ). i dont know, where this numbers are coming from and i dont think 23 should equal 7! what am i missing?
Test Results: Sum of Digits / Digital Root Basic Test Cases 23 should equal 7 957 should equal 6 132213 should equal 6 493222 should equal 2 Completed in 0.09ms Completed in 0.11m
The first value in the error message is what your function is returning instead of the expected value (the other one). Print the input, make sure you're not using a global var and read this: https://docs.codewars.com/training/troubleshooting/
This comment has been hidden.
That's a problem with your code, not a kata issue, please read this: https://docs.codewars.com/training/troubleshooting/ and use markdown formatting and mark your post as having spoiler content next time. Print the input, it wasn't 10.