14 Ways to Reverse a String! (And solve the exercise on Exercism)

  Рет қаралды 11,788

Exercism

Exercism

Күн бұрын

Пікірлер: 58
@adityapalpattuwar
@adityapalpattuwar 10 ай бұрын
30:20 Displayed code has compile error. You need to add 'char' keyword before '[input.Length]' - > Span chars = stackalloc char[input.Length]; Thanks for the detailed video.
@exercism_org
@exercism_org 10 ай бұрын
Ah - nice catch. Thanks for letting us know. Looks like it's been updated in the approach already, but we can't change the video now sadly.
@khoguan
@khoguan 10 ай бұрын
That C++ solution is efficient both time- and space-wise. But to make C++ handle UTF-8 strings is still a hassle.
@exercism_org
@exercism_org 10 ай бұрын
Yeah - agreed!
@daniel1564..
@daniel1564.. Жыл бұрын
Now I really understand the benefits of using StringBuilder, thank you for that detailed and exploratory overview of solutions!
@exercism_org
@exercism_org Жыл бұрын
Awesome to read! Thanks for letting us know :)
@rsalmei
@rsalmei Жыл бұрын
The key in the C++ one, for me, is not that it does it in less iterations, it is that it does it in-place, without allocating any extra memory.
@ErikSchierboom
@ErikSchierboom Жыл бұрын
True. Many languages don't support mutation of strings.
@TroyLaurin
@TroyLaurin Жыл бұрын
I agree with this sentiment, and disagree with the performance analysis in the video. The algorithm may perform half as many iterations, but it does twice as much work per iteration so the performance is practically the same compared to a version that iterates and copies character-wise over the whole string. It doesn't even avoid allocating extra memory, because the parameter is defined using copy semantics. The input string is copied into the function's stack on invocation, THAT COPY of the string is modified in-place and returned as the result of the function. Depending on a whole host of context, that value may need to be copied AGAIN at the call site of the function, unless the copy can be optimised away by something like NVRO. If I was the interviewer on this question and the candidate offered this solution without showing any understanding of what value is being modified and what copies are being made, that is a clear red mark, but not before prompting about the difference between copies and references. (note: only for jobs where this matters, which is rare. Then again, if you're applying for C++ jobs...)
@dolorsitametblue
@dolorsitametblue Жыл бұрын
Guys, you're killing it with the quality of the videos lately. Also, that little interlude at 23:54 is very funny =D.
@exercism_org
@exercism_org Жыл бұрын
Thanks so much! Yeah - at some point I'll have to put together an out-takes video of us talking over each other too. The 1sec lag while recording is too much for us to handle 😂
@ronaaron6935
@ronaaron6935 Жыл бұрын
As the developer of 8th, I'd have given a much different answer. First of all, just "s:rev" ... which does everything (much like the first, "cheating", answer). Or one could do 'null s:/ a:rev "" a:join' if one were inclined to write much code. Bruce's answer is esoteric, and perhaps meant to show off more techniques that go far beyond the needs of the exercise.
@ErikSchierboom
@ErikSchierboom Жыл бұрын
True. The aim of this video is not to showcase the language's idiomatic solution, but that there are different ways in which the exercise can be solved. We'll be sure to mention this explicitly going forwards.
@glennjackman759
@glennjackman759 Жыл бұрын
18:40 -- 8th: -- s:len -- s is not the input string, s is the namespace for string "words" (aka functions) -- s:len is the string length of the string at the top of the stack.
@ErikSchierboom
@ErikSchierboom Жыл бұрын
I have to start reading up on 8th!
@ronaaron6935
@ronaaron6935 Жыл бұрын
I was going to say, but I forgot...
@karo4131
@karo4131 Жыл бұрын
I really enjoyed the video. I was hoping to see the Python solution, it's pretty similar to Julia: def reverse(string): return string[::-1]
@ErikSchierboom
@ErikSchierboom Жыл бұрын
That's a nice one! Almost identical than the Julia one, but even more succinct.
@robert36902
@robert36902 6 ай бұрын
While I've never had to reverse a string to solve an actual problem in my programming career so far, this exercise shows important points in string handling that are good to know in order to correctly process strings that may contain arbitrary Unicode. After all, you want your code to be able to handle names of any person or city, not just those whose name can be represented with ASCII characters...
@NadCAtarun
@NadCAtarun Жыл бұрын
No recursive version? Base case: if length < 2 return the string unchanged. Recursive case: return last char + reverse(string[1::-1]) + first char
@ErikSchierboom
@ErikSchierboom Жыл бұрын
We probably should have added one, sorry!
@NadCAtarun
@NadCAtarun Жыл бұрын
It's okay @@ErikSchierboom ! I'm just a huge recursion buff 😉
@ErikSchierboom
@ErikSchierboom Жыл бұрын
Well I am too, which is why I should not have forgotten! :)
@NadCAtarun
@NadCAtarun 11 ай бұрын
@user-tx4wj7qk4t The point of the #48in24 challenge is to experiment not only with different languages but with different ways of solving the problems... What's wrong with using recursion in that context, then? Why should I care about the single responsibility principle or data coupling in the context of this challenge?
@NadCAtarun
@NadCAtarun 11 ай бұрын
@user-tx4wj7qk4t "better code" is such a context-dependent and subjective thing. You can value runtime performance, flexibility, legibility, style cohesion, resilience, composability, security... Ever heard of code golf? That makes my skin crawl, but you won't see me bother code golfers with all the code qualities they're throwing down the drain to have fun. Please let me enjoy my recursions in peace.
@GiriPrasath.D
@GiriPrasath.D Жыл бұрын
In python def rev_string(word): return word[::-1]
@canopusinthenorth
@canopusinthenorth 4 ай бұрын
In Golang section: Small correction, rune is not just a codepoint representing a byte but it could be a multibyte codepoint, which is why indexing into a string is not a good idea.
@ulissescruz5540
@ulissescruz5540 10 ай бұрын
I thought that the Go solution using `runes` would also work in reversing words with graphene. Doesn't the `rune` concept treat a graphene as a single unit as well?
@exercism_org
@exercism_org 10 ай бұрын
I think not. Graphemes are clusters of unicode codepoints. A rune is a single codepoint. So in Go, a grapheme is a slice of runes. This is a nice example: go.dev/play/p/5J32XwYJulh
@ulissescruz5540
@ulissescruz5540 10 ай бұрын
@@exercism_org Thank you for the great example. Now I think I understand runes better.
@exercism_org
@exercism_org 10 ай бұрын
Awesome. They're a really confusing topic! This was an interesting discussion the other day on the forum about them too: forum.exercism.org/t/potential-misleading-information-on-the-golang-runes-chapter/10082
@edmundbertram8446
@edmundbertram8446 Жыл бұрын
Why do you say the string builder should, in the java solution, have been called with an input string length? There is no specified length of string in the instructions.
@TroyLaurin
@TroyLaurin Жыл бұрын
When the function is called, you know the length of the string that was passed in, so you know what the length of the result will be.
@ErikSchierboom
@ErikSchierboom Жыл бұрын
Yes, this is precisely it! The reversed string's length will be equal to the input string's length, thus passing in the input string's length as the capacity for the StringBuilder will be exactly right.
@ahans123
@ahans123 Жыл бұрын
C++ has also std::reverse, which essentially does the std::swap internally. It would be called as in `std::reverse(str.begin(), str.end());`. But maybe you'd call that cheating as well. ;-)
@ErikSchierboom
@ErikSchierboom Жыл бұрын
Yeah, most languages actually do support reversing using a built-in function or method. I showed the std:swap version as it was a great way to show the classic algorithm.
@tamhuynhthanh874
@tamhuynhthanh874 8 ай бұрын
for Rust: pub fn reverse(input: &str) -> String { let mut reverse_str = String::new(); for c in input.chars().rev() { reverse_str.push(c); } reverse_str }
@stefanwaldmann7636
@stefanwaldmann7636 Жыл бұрын
When using StringBuilder in Java, this would also work: (however I suppose that would count as cheating, too... ;-) public String reverse(String s) { return new StringBuilder(s).reverse().toString(); }
@exercism_org
@exercism_org Жыл бұрын
Interesting! Is this better than s.reverse() in terms of speed and allocations?
@stefanwaldmann7636
@stefanwaldmann7636 Жыл бұрын
The String class itself does not have a reverse() method. The implementation within the StringBuilder uses the same algorithm as the one from C++ shown in the video (swapping characters in place). However it's necessary to instantiate the StringBuilder and convert the result back to a String object again. Also, the version above instantiates a StringBuilder with a capacity of s.length() + 16. So an even better version (if you care about the additional 16 characters) with a capacity of only s.length() would be: new StringBuilder(s.length()).append(s).reverse().toString();
@exercism_org
@exercism_org Жыл бұрын
Nice. Thank you for explaining!
@ragectl
@ragectl Жыл бұрын
Rust works well with graphemes
@ErikSchierboom
@ErikSchierboom Жыл бұрын
Absolutely. A lot of languages do actually, especially the more modern ones.
@aedaed-f4x
@aedaed-f4x Жыл бұрын
Bonsoir, s'il vous plaît j'ai besoin de votre aide, je veux faire quelques exercices en le langage C++ dans votre site puis savoir mon niveau par rapport aux solutions des autres, pouvez vous m'aider s'il vous plaît .. je sais pas les étapes pour faire les exercices; le lieu exact dans le site.. et merci infiniment pour vos efforts..
@exercism_org
@exercism_org Жыл бұрын
Bonjour :) Vous pouvez résoudre des exercices C++ dans notre éditeur en ligne sur exercism.org/tracks/cpp. Si vous êtes bloqué, vous pouvez demander de l'aide en utilisant #get-help sur Discord (exercism.org/r/discord). Je recommande cependant de traduire d'abord vos messages en anglais (puis de traduire leurs réponses) pour augmenter les chances que les gens vous soutiennent car nous n'avons pas beaucoup de francophones. --- Hello :) You can solve C++ exercises in our online editor at exercism.org/tracks/cpp. If you get stuck, you can ask for help in #get-help on Discord (exercism.org/r/discord). I recommend translating your posts to English first though (then translating their responses back) to increase the chance people will support you as we don't have that many french speakers.
@aedaed-f4x
@aedaed-f4x Жыл бұрын
@@exercism_org Vraiment merciiiii énormément, d'accord je vais suivre vos recommandations.. juste je veux savoir est-ce que c'est nécessaire d'inscrire dans votre site pour éteindre ce que j'ai demandé dans mon 1 er msg ou non ? Parce que, hier, j'ai trouvé votre site exercism à pour but de résoudre les 82 exercices en C++ puis savoir mon niveau.. mais je sais pas tous les informations et les étapes pour faire ça.. je suis vraiment désolé d'avoir autant parlé 😢 et merciiii, je veux juste les étapes.. Autre fois, je vous réitère ma grande gratitude..
@exercism_org
@exercism_org Жыл бұрын
Oui, vous devez vous inscrire et vous pourrez ensuite suivre le programme. Tout est gratuit. Si vous êtes totalement nouveau dans la programmation, vous aurez probablement un peu de mal et cela vaudrait la peine d'apprendre d'abord sur des sites plus basiques. J'envisagerais également un langage plus "convivial pour les débutants" comme JavaScript ou Python. Cependant, si vous savez déjà programmer un peu, alors notre cours de C++ sera parfait pour vous :) --- Yes, you need to sign up and then you can work through the syllabus. It's all free. If you're totally new to programming, you will probably struggle a little bit though and it would be worth learning from some more basic sites first. I'd also consider a more "beginnner-friendly" language like JavaScript or Python. However, if you can already program a little, then our C++ course will be great for you :)
@aedaed-f4x
@aedaed-f4x Жыл бұрын
@@exercism_org j'ai commencé la programmation depuis longtemps et d'abord j'ai terminé le C++ (ou plutôt, j'ai terminé les cours de C++ dans un site) et je veux faire qlqs exercices .. mais hier, comme j'ai dis avant, j'ai trouvé votre site, afin de faire qlqs exercices et connaître mon niveau par rapport aux solutions des autres, .. Bref, merci beaucoup à vous .. (j'attends votre réponse à propos des étapes que je dois suivre et mille mercis! Et désolé si je vous ai dérangé)
@rsalmei
@rsalmei Жыл бұрын
You could have included Rust...
@ErikSchierboom
@ErikSchierboom Жыл бұрын
We could, but we only have a limited number of solutions (and tracks) to feature. We featured Rust last week, and we'll feature Rust in many other weeks to come.
14 Ways to Solve Raindrops (FizzBuzz, but harder!)
50:24
Exercism
Рет қаралды 8 М.
6 Ways to Code Circular Buffers
47:56
Exercism
Рет қаралды 3,5 М.
Сестра обхитрила!
00:17
Victoria Portfolio
Рет қаралды 958 М.
VIP ACCESS
00:47
Natan por Aí
Рет қаралды 30 МЛН
Mom Hack for Cooking Solo with a Little One! 🍳👶
00:15
5-Minute Crafts HOUSE
Рет қаралды 23 МЛН
8 Ways to Solve Zebra Puzzle (feat. Genetic Algorithm!)
1:17:15
Exercism
Рет қаралды 1,9 М.
Zig for Impatient Devs
9:48
Isaac Harris-Holt
Рет қаралды 130 М.
3 Types of Algorithms Every Programmer Needs to Know
13:12
ForrestKnight
Рет қаралды 529 М.
Ditch your Favorite Programming Paradigm
6:08
Code Persist
Рет қаралды 215 М.
Dear Functional Bros
16:50
CodeAesthetic
Рет қаралды 577 М.
12 ways to Convert Arabic Numbers to Roman Numerals
58:15
Exercism
Рет қаралды 3,8 М.
Never install locally
5:45
Coderized
Рет қаралды 1,9 МЛН
The 7 Levels of Math Symbols
14:03
The Unqualified Tutor
Рет қаралды 29 М.
Сестра обхитрила!
00:17
Victoria Portfolio
Рет қаралды 958 М.