5 kyu
Closest and Smallest
110 of 3,343g964
Loading description...
Fundamentals
Sorting
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.
in my vscode this exercise do well. I don't understand why there is an eror in here.
We do not know this either, and without seeing your code, we cannot tell why it is wrong.
This comment has been hidden.
Nice kata, doing these type of coding challenges for fun is always rewarding.
Precision: New to c# $$$$ I am having an error System.FormatException : Input string was not in a correct format. This is on the unit test code line cdecode.Helper.Array2DToString(ClosestWeight.Closest(s)) The code itself run without any error and i have not change the output type so i am returning int[][] and here the return return new int[][] { result[index], result[index+1]}; I guess the Helper method is from Nunit frawework but quick search unsuccessful. So what could cause the cdecode to throw error ?
very good kata!!!
Does anyone know what could be happening in this situation? I received the correct answer on my local env, but when I test it here, it returns a reversed array. For example:
Expected: '[[10, 1, 154], [10, 9, 37]]', but I got: '[[10, 9, 37], [10, 1, 154]]'
On my machine, I normally get: '[[10, 1, 154], [10, 9, 37]]'
i fix sort array and most test passed, but i have another problem different result on local and serv env.
I think it can be: Node.js Version Dependencies and Packages Environment Variables System Locale Platform-Specific Behavior
python new test framework is required. updated in this fork
Approved by author
C fork
Approved!
Very nice Kata. Good for learning Scala. Thank you!
Very good Kata! Thanks to author!
C#:
Sample tests throw an error despite the correct code passes random tests
System.FormatException : Input string was not in a correct format.
Stack Trace at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type) at System.Int32.Parse(String s) at ClosestWeight.<>c.b__0_0(String x, Int32 i) at System.Linq.Enumerable.SelectIterator[TSource,TResult](IEnumerable
1 source, Func
3 selector)+MoveNext() at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable1 source, Int32& length) at System.Linq.Buffer
1..ctor(IEnumerable1 source) at System.Linq.OrderedEnumerable
1.ToArray() at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source) at ClosestWeight.Closest(String strng) at ClosestWeightTests.test1()Only your solution throws an error. I can be wrong but I think the problem is in your code but I have no time to investigate it.
Hi, my implementation in rust passes all basic_tests, however it fails with the random tests, please can someone explain me why this string "478117 478 234955 249 761812 53 178807 396 728614 909 825796 928 157818 742 810150 842 330106 381 51786 167 742499" returns the following:
assertion failed:
(left == right)
left:"[(13,14,742)(13,17,330106)]"
, right: `"[(13,13,742)(13,16,330106)]As you can see the indexes are off by one, I can't figure out what I'm doing wrong, I think the correct answer is "[(13,13,742)(13,16,330106)]", is this is a mistake in the test suite for rust? or am I missing something?
The random test are marking me as wrong when its not How is this possible? When I try local I have the expected result. Please help!
This comment has been hidden.
Your code does not always respect that ordering
Spend 3 days on this. I like this kata
Nice 5-kyu kata, I came up with a simple comparison function and let Python do the work.
Nice kata about programming, makes you think through the language. A breath of fresh air in between all those gotcha katas.
amazing challenge !
so i wrote the code and tested it one by one and works. but then test results show: "TypeError: Reduce of empty array with no initial value". someone care to explain?
Do you use
reduce
in your code? is there a chance you callreduce
on an empty sequence?thanks finally solved it. didn't really notice the first test on the empty string
hmph..done at last.
Can someone explain the task more clearly? I get the summing the digits to find the "weight" part, but after that its not clear what its trying to say. Any help would be appreciated.
u need to retrieve the pairs with minimum weight difference between them and having the lowest index as well as weight
had to write like 10 helper functions but i did it! thanks for the awesome kata
Why output is string in perl not nested anonymous arrays?
Perl is not the only one with strings but is it a sufficient reason?
The random tests in Python could contain trailing spaces, e.g. "24 4820 10380 21 259 1 " I didn't expect this, and nothing in the description or the standard tests led me to expect it. It could be nice to add a specific test case for it.
Description says:
Nothing is said about trailing spaces or not. You could have simply taken a split function without separator. Nevertheless I added such an example in "TEST".
Thank you! I've learned something new about the split function, so this was a good exercise. It was just unpleasantly surprising to see this test failure that I didn't expect.
While performing this task, I learned that the JS sort function works differently in modern browsers and in the old Node.js. I had to write an additional sorting condition.
By the way, it calls "unstable sort algorithms". Stable sorting - only Chrome 70+, Firefox 79+, Safari 10.1+.
testing(closest("89998 187 126159 175 338292 89 39962 145 394230 167 1"), [[13, 3, 175], [14, 9, 167]]) Can someone explain why? My resutl is [[16, 1, 187], [17, 5, 89]], i dont know why its bad, weights are the same but in my reuslt index are closer to 0
Why do you say weights are the same? 13 and 14 are smaller than 16 and 17.
Funny kata to practicing sort. Thanks.
maybe it's my english but i think it could be better explained
test cases might help to understand the question.
There's even more completely nonsense in this Kata. In the Notes, you find a hint that for empty string "" you should return something - but what about the case where only ONE number is in the string? This Kata needs serious rework. Please.
Read the description: "a string strng of n positive numbers (n = 0 or n >= 2)".
I find this Kata to be particulary hard to understand and read. It's not pleasant and well defined at all.
For example, the third criterium reads: "and with the smallest indices (or ranks, numbered from 0) in strng"
What exactly is that? We are talking about two numbers... so, is the sum of their indices to be minimized? If index 1 and 1000 AND 2 and 10 are closest by all other rules, does 1 and 1000 win over 2 and 10?
Sorry, but I dislike this Kata already before I start to program...
Also, the Kotlin translation lacks proper use of the right datatypes - if TWO things are to be returned, one should pick a Pair, not an Array.
To me a poor Kata is one where it takes longer to understand the problem than it does to come up with a solution.
I completely agree. The three criteria are very poorly defined, and the explanation is also full of holes.
small typo- "because 2000 and 103 have for weight 2 and 4, (their, not ther) indexes in strng are 4 and 0."
Fixed, thanks
The random tests' input contain a trailing whitespace which I don't think was intentional.
It's not uniform to the basic tests that have no trailing whitespace with their inputs.
When reporting an issue, please, state the language.
The description says the input is:
Nothing is said about trailing spaces or not. In Basic Tests and in Random Tests you get a string of n positive numbers; the trailing space, intentional or not, doesn't change anything and as far as I know nobody among the 438 people who passed the Python kata complained.
PS: BTW (no offense!) your
" "
is not useful (and maybe could be wrong in some cases) in split function.Ok, that's a good point. It didn't occur to me that other people didn't use split because I was so deep into the problem. Thank you and my bad!
This happends at least in Rust.
To change the string into an vector of long long values I use std::stoll. My code works well for the test cases, but if I do Attemp stoll throws an exception. I deletet the non digit letters at the beginning of the Random test. Also the exception is thrown when the code tries to convert the last number of the string in the random test into a long long value. Has anyone experienced the same problem?
Test for (462835, 148, 467467, 128, 183193, 139, 220167, 116, 263183, 41, 52) is broken! Please fix this test. For correct answer [ (13, 1, 148), (13, 5, 139) ] there is an error: caught std::exception, what(): vector::_M_range_check: __n (which is 4294967294) >= this->size() (which is 0). If swap element of answer, there is an error: Expected: equal to [ (13, 1, 148), (13, 5, 139) ] Actual: [ (13, 5, 139), (13, 1, 148) ].
I'm sorry but I don't see where your problem is:-( The test
is correct. I tried a few passing solutions and they worked fine.
This comment has been hidden.
It was crazy kata but I solved IT! ^_^
OK, solved!
In my C solution the test always says: Test Crashed Caught unexpected signal: 6 Completed in 0.0000ms STDERR setup.c:46:21: warning: comparison of integers of different signs: 'int' and 'unsigned long' [-Wsign-compare] for (int i = 0; i < strlen(str); i++) { ~ ^ ~~~~~~~~~~~ 1 warning generated. munmap_chunk(): invalid pointer
On my computer it runs perfectly, also with valgrind, I cannot find a memory leak. I checked the mallocs, but everything seems to be fine. Maybe I should increase/decrease the size of the allocated memory?
it's not about allocation, it's about casting.
strlen()
returns asize_t
value, comperable tounsigned long
. so, just change the type ofi
in yourfor
loop and that should do itWell I spent more time trying to understand the question than coding, hacking it together piece by piece as my understanding of the question evolved. I notice a lot of problems on this site are like that. Briefer, simpler to understand questions but with complicated solutions would be a far nicer thing to encounter.
(Sorry for my English, I am Russian)has complete that task in JS, BUT what is required to return:
"Output:
an array of two arrays, each subarray in the following format: [number-weight, index in strng of the corresponding number, original corresponding number instrng]" The second required number in subarrays is INDEX IN STRING!, not in array, but tests contain exactly indexes of arrays, which is returned as result of using method "split" in JS (or smth like that on other languages). Tell me why I'm wrong ^_^.
Yes there is some ambiguity in the formulation... Let us take the first test in "RUN SAMPLE TESTS":
testing(closest("456899 50 11992 176 272293 163 389128 96 290193 85 52"), [[13, 9, 85], [14, 3, 176]]);
Look the answer
[[13, 9, 85], [14, 3, 176]]
.9
corresponds to85
which is the substring with "index" (language abuse for "place" or "rank") 9 (numbering from 0) in the input string.3
corresponds to176
which is substring with "index" 3 in the input string.You can read
[number-weight, index in strng of the corresponding number, original corresponding number in strng]
as[number-weight, place (or rank) in strng of the corresponding number, original corresponding number in strng]
.Sorry for this ambiguity but I thought the examples made it clear.
Thank's for your answer, I'm just a beginner and will appreciate it.
Currently using a function to compare values using an iter() to keep one step ahead. When testing I get:
STDERR Traceback (most recent call last): File "main.py", line 8, in testing(closest(""), []) File "/home/codewarrior/solution.py", line 9, in closest lowest_weights = closest_pairs(lst, 0) File "/home/codewarrior/solution.py", line 28, in closest_pairs next(ahead) StopIteration
The code works when I run it on my computer. Does anybody know why this happens and how to remedy it?
This comment has been hidden.
Not a kata suggestion
C version of random tests (№22, but may be more...) is BUGGED:
Screenshot: https://imgur.com/a/BNz5Vok
Please fix it asap @g964 as this is the second time I'm getting a broken random tests version for C in
your kata (first one being k-Primes and I'm not the only one there).
edit: the problem is
strng: '12719 14978 18158 6578 17606 18577 16018 17959 14215 16124 12484 '
in test 22 (+) has an extra space at the end of it.For the string given in your edit:
At last I will say the same thing @Steffan153 told you for the k-prime kata: many people (amongst them "smart" people) have passed the kata so one can be quite sure that the problem doesn't come from the kata but certainly from your code. I see you are new at CW and I am sorry that you have problems.
Do not mutate the input!! That's what happens!
@g964 It wasn't the input, it was
char** split(char *str, const char *delim, int *length);
prewritten function: somehow if you don't specificaly malloc int* length before passing it
to this function, on space-ending strings it breaks. Like litteraly the FUNCTION stops
working correctly for the next call.
P.S.: Are we even supposed to use those? And if so, than why are there no comments as to
what those prewritten functions actually do? If not, than why are they present
in 'Sample Tests'?
No matter what I try I get the following error (this is the error right after a reset):
main.cpp:8:68: error: out-of-line definition of 'closest' does not match any declaration in namespace 'Closest' std::vector<std::tuple<int, unsigned int, long long>> Closest::closest(const std::string &strng) ^~~~~~~ 1 error generated.
Am I missing something? Sorry if this is a basic question but I'm not too familiar with namespaces and am not sure where to look. I've been searching for several hours now. Thanks for any help!
Hello again, I figured out the issue and wanted to help anyone else who's having the same problem. The kata starts with:
std::vector<std::tuple<int, unsigned int, long long>> Closest::closest(const std::string &strng)
Removing the "Closest::" fixed the problem for me. I don't know why so if anyone who knows can let me know I'm interested in why that worked!
I guess it's because closest() is a local function and does not belong to any namespace. Probably just a typo. Probably...
My result is like that Array ( [0] => Array ( [0] => 8 [1] => 5 [2] => 134 )
) But the test always show Failed asserting that two arrays are equal. Expected: Array ( ) Actual : Array ( 0 => Array (...) 1 => Array (...) )
I cann't understand the reason. By the way, I codes by php
don't you want to mark it like 'issue'?
Sorry but issues are for problems in the kata not for problems in code. Cheers.
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.
Hi @g964.
My comparator completely ignores the
index
so I expected there would be some tests which fail due to that. The fact nothing failed meant I assumed such tests were missing.When I tried using my solution for that example I was very surprised it still worked!
But how? So I've been googling a bit more about it. Apparently the behaviour of retaining the original index order is called a Stable Sort. Apparently Java implements a couple of sorting algorthims and so because I sort my "Stuff" objects by Comparator it is internally/deliberately using a "Stable" merge-sort.
Which means it all just works. Seems it's not a fluke after all. Seems I was getting something for nothing (stable index order) without even knowing it!
OK, good. So no need to add new tests and I think I can consider the issue as resolved unless you think the opposite.
Well, it's still not clear to me if any of the existing fixed test are testing the index-order rule. But if you say they already are then there is nothing to do, and sorry for the false alarm.
I added a few tests... in case. Feel free to add some of yours if you want.
i tested in my vs2013 is passed ,but here i am not passed ,what's happen ?
Shell is missing sample tests. This time I needed 10 before succeeding. :O
Fixed, thanks again but I can't believe I forgot so many sample tests:-(
There were some kata 7 too, but it was so simple I didn't report it — the description had test cases, so it was a tiny TDD exercise in itself. I'll let you know if I stumble upon any more.
Thank you so much!
This comment has been hidden.
Please surround multi-line code snippets with lines of three backticks (```).
You are using
find(weight_1_pos + 1, weight.end(), weight_2)
to get the position of the larger number. But if in the input the larger number comes before the smaller number,find(...)
will not find it and return the end iterator.All the sample test cases are passing. But on Attempt, 180 Passed, 41 Failed, 1 Error. Example of failure - Expected: '[[9, 7, 135], [9, 9, 126]]', instead got: '[[9, 7, 135], [9, 10, 36]]'
Is it possible to get the arguments for this example?
Print the input.
This comment has been hidden.
7+9 < 7+10
Why can't I use the String module in OCaml?
What happens and what's your code? I've just tried the built-in String and Batteries too - everything looks normal.
Your code compiles when I replace your
split_on_char
by the built-inString.split_on_char
.Your code fails because you return a
list
of all the tuples(weight, idx, number)
, but only the 2 closest should be returned, structured as a tuple of 2 arrays[| weight; idx; number |]
i passed all the tests even random ones but i am getting this STDERR: Traceback: in in tests in closest ValueError: invalid literal for int() with base 10: '' i cant find out what this error is for.. help is much appreciated.
issue some case some where has white space so need to account for that
This comment has been hidden.
nvm i found my issue...after i unlocked the solution... :'( ugh so close but so far
Why I always get
*** Error in `/home/codewarrior/solution': munmap_chunk(): invalid pointer: 0x00000000004020a3 ***
I've test my code on my computer and it works without any problem.
did you find out your problem?
On Attempt
testRandom
Log
Random Tests
input: 213661 145 482403 149 163732 130 14079 46 209766 121 61
Error: Call to undefined function weight()
What is the function weight()?
Modified something this morning but I made a mistake in a name. Should work now. Please tell me and if it works could you mark the issue as resolved?
All fine! Thank you.
This Kata's tests are invalid for the specifications in PHP. It creates a test in the random tests every time that doesn't follow the expected output. EX) Failed asserting that two arrays are equal. Expected: Array ( 0 => Array ( 0 => 1 1 => 10 2 => '100' ) 1 => Array ( 0 => 1 1 => 3 2 => '10' ) ) Actual : Array ( 0 => Array ( 0 => 1 1 => 3 2 => 10 ) 1 => Array ( 0 => 1 1 => 10 2 => 100 ) )
As you can see. The test's expected output expects two numbers with the same weights to not be sorted by index, which is a requirement of the previous tests.
Should be fixed now. Tell me if it works and if so could you mark the issue as resolved? (Index was compared as strings and not as numbers...). Thanks for your post.
That fixed it.
hey, for python, in the random string tests, in some cases the numbers repeat (not the weights). How am I supposed to deal with this? I modified my code to ignore repeats, but then it fails in that way too.
If numbers repeat they have the same weight but not the same index.
When you post a question don't label it as an issue. You then make the author lose points. Furthermore you could have seen at the top of the page that 50 guys passed the kata Python so we can be sure there are no errors in the tests. Good luck!
I think that the c++ tests have the wrong values in them. For example, the second test case looks like this:
s = "456899 50 11992 176 272293 163 389128 96 290193 85 52"; e1 = std::make_tuple(13, 9, 85); e2 = std::make_tuple(14, 3, 176); e = {e1, e2}; dotest(s, e);
The smallest weight is given by the "50" value at index 1 in the string. It should have weight 5, right? There are three or four of the tests that have this issue.
Also, the syntax of the starting function is incorrect. The namespace qualifier is not required if you're defining the function inside the namespace. It starts as this:
std::vector<std::tuple<int, unsigned int, long long>> Closest::closest(const std::string &strng) { // your code }
It should be:
std::vector<std::tuple<int, unsigned int, long long>> closest(const std::string &strng) { // your code }
The current implementation doesn't build because of this.
Expected: equal to [ [unsupported type], [unsupported type] ] Actual: [ [unsupported type], [unsupported type] ] why it happened this???
It happens when there is a flaw in your code.
You're talking about the C++ version, right?
@g964 You can use the full power of igloo / snowhouse by putting the following in the "Preloaded" section:
Then
becomes
OK, lots of thanks! I will try. How do I use it in the tests?
Igloo uses
showhouse::Stringizer
to display actual and expected values. If there is a specialization ofshowhouse::Stringizer
(in this case forstd::tuple
) igloo will automatically use it. You don't need to modify the tests.Cheers!
OK, good to know!
This comment has been hidden.
Doesn't seem easy to test matrix equality with expect_equal. I changed a bit the random testing function. Could you tell me if it works better for you now? (My solution passed the first version of random tests without problem but is it a proof?) New publishing seems to take long.
now it passes all the tests! thank you. great kata! btw I am double checking your solution to see what might cause the error
Thanks for your post. Good to double check but the first random testing function is no more there. I used in it something like
expect_equal(matrix1, matrix2)
. I replaced it by something like the fixed tests function. Tell me if you find something!Our returns have the same elements but were not taken as the same.
Fun Kata! Thanks g964!
Good, thanks for your post!
JavaScript's test cases occurs the issue like:
You mutated the input.
But strng is only a copy of string, and I didn't try to modify the input string. All operation upon strng has no any side-effect. And I didn't use any global varible. Orz...
It shouldn't happen though...
Maybe you can post your code (marked with spoiler)?
Got the same issue. In my case it was because I was overwriting Array.prototype.flat. Even though it says it's using node8 and flat was introduced in v11, it still a had problem with that somehow. So avoid overwriting any build-in objects.
(JS) I pass all of the example test cases, but when I run the full suite with random tests, the expected value is
[undefined, undefined]
on every single test.I tried a few solutions and had no problem. 24 guys passed the JS kata, enough to say that all is certainly fine. Do you modify the input string?
there is a bug in test;
Yes, I got some troubles with it too. On the output formatting paragraph, it says : "The two subarrays are sorted in ascending order by their number weights if these weights are different, BY THEIR INDEXES IN THE STRING IF THEY HAVE THE SAME WEIGHTS."
The uppercase part of the paragraph is a lie. The only sort you have to follow is the one on the weights.
Thank you, I just lost 30 minutes wondering why my solution wasn't working.
That's all right.
This comment has been hidden.
Hi, Didn't find how to report a cheat solution so I thought I would write here. The solution in Ruby by Poilon is clearly not trying to solve the actual problem but "cheat the way through".
I don't know enough Ruby to understand how it works but maybe it can be prevented with tests.
Hi.
I have an issue with this Kata in Python.
The code I wrote works on an external IDE but not when I try to submit the code here. I get the error :
I tried a few solutions and had no problem.
The first test case passes an empty list. That's probably the reason.
This comment has been hidden.
Your solution is compiling and running on Codewars too. It's just that it's getting the answer wrong -- and the Codewars test framework is reporting this rather ungracefully, because it doesn't seem to know about tuple types in C++.