I used to be really frustrated with how difficult to understand academic papers are, but after gaining enough knowledge, I'm now a little more sympathetic - it's really easy to tersely express ideas with complex language, simplifying them requires a lot more effort and is almost always more verbose.
It would be nice if someone would keep a dictionary for all the field specific words that have quite precise meanings. That way ppl could reference that source instead of spending one or more paragraphs explaining a single word or notation. Or leave it as an exercise for the reader to figure out what something means. edit: before ppl explain the obvious fighting over the meaning of words this would produce, I know but a potato can dream.
It may be field specific, but I honestly rarely encounter papers, that are complicated for the sake of being complicated, as some kind of intelectual voyeurism. Most of the difficulty comes from not knowing the field, which cannot be easily overcome I'm afraid.
@@rumplstiltztinkerstein it's likely that until AI is fully self-explainable and deterministic society will continue to rely on human correction and oversight at least for success critical projects
One from my brother: Code purpose: Every time list is changed, sort list. Problem: sorting list counts as a list change, producing infinite recursion. Solution: catch exception when hitting max recursion depth, assume list is sorted at that point, and continue from where you left off. As he says: "if it works, it works!" [He did fix it the next day when he worked out the proper way to do it.]
5:31 For those wondering, this is Minecraft enchanting table language (aka Standard Galactic alphabet), which is actually not a language but just a font that looks all funky
i hate that it's known as the minecraft language, rather than the commander keen language. but i guess it's nice that some people might be led to discover commander keen throught it.
i wrote a JS "translator" for this once - it's actually comprised of unicode. what's worse is some ASCII chars actually are represented by multiple SGA chars which broke my poor virgin JS dev soul
I’ve done it ¯\_(ツ)_/¯ Back before I’d set my comment-block to the best ever keyboard shortcut (Shift+Alt+A) Protip: you can set a block comment shortcut in SSMS. Sadtip: you cannot use the same shortcut to block uncomment :( Mildtip: • (Shift+Alt+A)->block comment • (Ctrl+Shift+Alt+A)->block uncomment
i do that all the time in unity, all it does is ignore the function until i finish it so i can run the game, if that is at the end a jususst use return but some ides complain that there is code after the return
in java, you could change false to returning always true (and vice versa) via reflection, so this if block could actually be executed. ofc pointless, just saying for funsies
1:34 I actually did that recently. The stack trace sometimes contained personally identifiable information, so I caught and rethrew the error to get rid of it in our logs.
I literally had seen code from a colleague with constants like this: int OneSecondWaitTimeout = 1; int TwoSecondWaitTimeout = 2; int FiveThousandMillisecondsTimeout = 5000; Not a joke, it exists and everytime I review code from this guy, I die inside.
I take it this was used one time in one file, but if any one of these were used in ~100 places across several files, it makes sense to capture it in a variable.
@@Asto508 Not local; global. That's what I meant with "100 places across several files". Magic strings and numbers are a major PITA. It's better to group them in one place and refer to them via constants or enums. If by your post you meant that your colleague keeps them _in one scope_ then yeah, that's dumb AF and I feel your pain; I get those as well. ``` const isLoggedIn = user.logged_in if (isLoggedIn) { ... } ``` _fukme_
@@Honken Well, if the constants are actually some very important number, then I can see your point, but we are literally talking about "1" or "2" in constants named "One" and "Two".
@@Asto508 The same principle still applies; if they are used hundreds of times, by having them constant you have one uniform value instead of hundreds of arbitrary values, hence the word 'constant'. If we need to change TIMEOUT from 2.0 to 5.0, that's a one line change. If we have to dig through tens of thousands of lines of code and find every `timeDiff.Seconds >= 2.0`, we will be wasting a lot of time and run the very palpable risk of missing one and heisenbug ourselves into pager duty on Christmas. As dumb as it sounds, having a constant/enum called One which is bound to the integer 1, if the references to that number is high, it's an investment well made.
I've seen this one java class that had a 6,500 line method with 5 layers of inheritance. Stuck right in the middle of the method were these two massive nested if blocks where they both were ~450 lines of if, else if, else crap. Best part was the second of the two if blocks was a copy and paste of the first with one comment saying "don't delete this because for some reason the code won't work without it," and you know what that person was right!
On my first ever project that wasn't trivial I had a similar situation where I needed to add else if instead of else or the code didn't work. To this day I don't know why that was the case as it was supposed to be a boolean condition. Anyways, long ago I rewrote that entire part of my project, so I no longer have that issue.
That sounds reasonable, though. At least you're changing the type of the exception and giving it a new context (or, in this case, escaping the hell that is Java's checked exceptions). Throwing a play Exception is just throwing the stack track and type away.
@@aenguswright7336 What do you mean? This is a very common way to solve it. KISS, keep it simple stupid. Why would you overcomplicate it for no reason?
5:42 Not only kids use Scratch, also some grown-ups that enjoy a challenge. There's a full RISC-V emulator written in Scratch that runs a tiny Linux distro. And when compiled to JS it is actually acceptably fast with a boot-up time of ~20s. On vanilla Scratch it takes longer than an hour to boot at which point I just cancelled it.
9:05 Just for fun I just challenged myself to do a FizzBuzz and I used an object with numbers as keys and the wanted strings as the values, iterating over the wanted number range and at each iteration iterating over the previously-defined object and checking if i is cleanly divisible by the number and if yes adding its associated string to an array. At the end of the iteration step I check if the aforementioned array is empty. If yes, I output the number and if not I join the array elements together with an empty string. Adding seven for "Bazz" was as easy as defining the object's key "7" as "Bazz".
6:38 Experts, please explain to me the difference between a Git rainforest and a primitive Git jungle. What are the most toxic bugs that can be found in there?
I don't know if this is right, but for the FizzBuzz question, I would have done it this way: conditions = {3: "Fizz", 5: "Buzz", 7: "Bazz"} for i in range(1, 101): result = ''.join(v for k, v in conditions.items() if i % k == 0) or str(i) print(result)
I used to do it branchless, thanks to bad habits i picked up from codeingame: for i in range(1,101): print( ("Fizz"*(i%3 ==0) + "Buzz"*(i%5 ==0)) or i ) There are so many ways to do it. Recursion: def fizzbuzz(i=0): if i==100: return print( ("Fizz"*(i%3 ==0) + "Buzz"*(i%5 ==0)) or i ) return fizzbuzz(i+1) Awful hashes: fizz = { str(n*3) for n in range(100//3) } buzz = { str(n*5) for n in range(100//5 } for i in range(1,101): print( fizz[i]+buzz[i] or i ) Generators too: fizzbuzzgen = ( ("Fizz"*(i%3 ==0) + "Buzz"*(i%5 ==0)) or i for i in range(1,101)) while fizzbuzzgen: print(next(fizzbuzzgen)) Without modulus and division: fiz = 0 buz = 0 for i in range(1,101): fiz+=1 buz+=1 print(("Fizz"*(fiz==3) +"Buzz"*(buz==5)) or i) fiz = fiz*(fiz!=3) buz = buz*(buz!=5) Hell even pure CSS (with LOADS of empty divs in html): .fizz-buzz { counter-reset: fizzbuzz; } .fizz-buzz > div::before { content: counter(fizzbuzz); counter-increment: fizzbuzz; } .fizz-buzz > div:nth-of-type(3n+3)::before { content: "Fizz"; } .fizz-buzz > div:nth-of-type(5n+5)::before { content: "Buzz"; } .fizz-buzz > div:nth-of-type(3n+3):nth-of-type(5n+5)::before { content: "FizzBuzz"; }
the thing is, the 'if/else' fizzbuzz solution is usually the most performant. It's just not scalable at all. Also if you add 'bazz' as 7 then would you also print 'fizzbuzzbazz' when the number is divisible by all of them?
It’s not the most performant. Use counters instead, which reset on hitting 3 and 5 and you remove %. Optimize it further and populate an array[n=smallest divisible number=3*5] with answers and write to output as many times as needed.
Catching and then rethrowing immediately is useful when you need a debugger trap because breaking on exception sometimes destroys the callstack legibility, I'm looking at you javascript. And then you forget it and push it to production.
In the Java case, the debugger trap is useful as setting a breakpoint at the end of a function doesn't get triggered if the stack is being jumped/unwound. There may be advanced debugger features that can do this, but its much easier to combine basic debugger functionality with basic code and set a breakpoint on that line so you can examine what's going on as the exception is being thrown. A very similar (but not exact) reason to do this is if the caught exception is checked and you're just rethrowing an unchecked, or a different wrapped checked (ugh) exception.
@@drewbabe If it hasn't changed it's necessary in Java to catch exceptions (elsewise the code will not compile), if you can't handle them you have to rethrow them. Thus the shown code is the only valid way in Java to escalate the exception upwards into runtime. It's not cringe in anyway, not every exception can be handled by a program, but needing to handle all exceptions leads to more safe code (defensive programming). I mean Rust does pretty much the same thing with an onEvent function instead of a catch block and people praise rust for this. Just because it's older way, doesn't make it worse.
@@MrDavibu I don't see how putting it in a try/catch block would change anything in Java. I don't know if it was ever different, but when I've worked with Java the way it works is that a function can't throw an exception unless you include "throws Exception" (or some subclass of Exception) as part of the function declaration, and if you do have that included as part of the function declaration then you don't need to include a try/catch block even if something within that function throws an exception.
When I wrote fizzbuzz for the first time I did it in Python in a way that you could pass the fizzbuzz function a dictionary where the keys are numbers and the values the strings to replace them with, so you could call it with {3: "fizz", 5: "buzz"} or {3: "fizz", 5: "buzz", 7: "bazz"} or whatever you like, with pretty much as big a dictionary as you wanted.
@@henry_tsai I think I described it poorly. You don't pass a dictionary with all the numbers. If you pass just {3: "fizz", 5: "buzz"} it will automatically replace all multiples of just 3 with fizz, all multiples of just 5 with buzz and all multiples of 15 with fizzbuzz. If you pass {3: "fizz", 5: "buzz", 7: "bazz"} it will additionally replace all multiples of 21 with fizzbazz, all multiples of 35 with buzzbazz and all multiples of 105 with fizzbuzzbazz. That is, assuming I added a maximum number parameter to allow it to output more than 100 numbers, which I don't remember if I did or not, and I don't know if still have the original code I wrote.
At about 7:40 into the video... I've heard of, seen and have unrolled loops for efficiency reasons to minimize the branch predictions, etc. Yet I don't think I've ever heard of or seen unraveling operations that can be calculated by simple iterators. I'd hate to have to be the branch predictor on the machine that has to run this code.
Sometimes at work (in Go) we write functions that take a pointer to a boolean as a parameter, usually for a simple filter that has three states (eg: when requesting customer list get free users / premium users / all users). Certain higher level functions always need a particular list, but you can't just pass true because it needs to be a pointer, so I call it like this: true := true myFunction( &true ) "If it's stupid but it works, it's not stupid." (/s)
One that always gets me: ``` if condition return true else return false ``` Or one where items were deleted from a collection in a set of nested loops and checks, e.g. ``` while true { for index in range { if (range[index] == itemToDelete) { range = range[0..index-1] + range[index..range.size] found = true } } if found break } ``` There are so many better options one can choose. One, assuming no need to preserve order or immutability is to reverse the iteration order and swap the found item with the last [unmatched] index and then just trim the collection to the new size.
@@Nathan-pl2cf You can still return directly with a double negation (e.g. JS) or type cast (e.g Python). If you can branch on a condition then you can also directly return a boolean representation thereof (true|false; 1|0; etc.) in most common languages. Personally I try to dispense with weak notions of type as soon as possible as these, in my opinion, are too frequently a source of bugs.
@@TheAndreArtus I agree, just wanted to point out that they weren't entirely wrong, depending on the language anyways. I would probably go with explicit casting over the ternary though.
For the FizzBuzz stuff, use a map with numeric keys and what should be printed. Use % key == 0, add value to variable and print at the end, printing the number if variable is empty. You're welcome.
What do you mean by " % key == 0"? You mean iterate over the key values and check if whatever number you have `% key` is 0? Then what's the point of having a map in the first place?
@@CottidaeSEA sure, but MH_VOID isn't using a map. That's just an array of tuples. Still, why would that be any better or worse than having just more if statements (presuming you do string concatenation)? I'd argue it's less readable unless you're getting into many more than 4 or 5 branches.
I think what he means with fizzbuzz and map and adding a 7 for example would be this: const condition = { 3: "Fizz", 5: "Buzz", 7: "Prime" }; for (var i = 1; i i % key === 0 ? value : "") .join(""); if (!answer) answer = i; console.log(answer); }
I have also done it in one liner (kind of): const conditions = { 3: "fizz", 5: "buzz", 7: "prime" }; for (let i = 1; i i % +key === 0 ? conditions[key] : "" ) ); console.log(line); } Or better to use an actual map here: const conditions = new Map([ [3, "Fizz"], [5, "Buzz"], [7, "Prime"], ]); for (let i = 1; i
@@twothreeoneoneseventwoonefour5 This is something i wrote quickly in the console and if its let or var here is so unimportant :D There are 1000 ways of solving this.
Yesterday i was refactorig some code written by a collegue and i found this gem. $files = [ ] foreach ($media_files as $file){ $files [] = $file; } return $files; Also the most evil definition of true/false ive ever seen is #define true (rand() % 2) #define false (rand() % 2)
Making a copy of a list to avoid leaking internal state or reference issues has many valid uses. You probably broke your colleagues code and caused a disaster due to naivety.
@@gregorymorse8423I was about to say that, unless php has some function like Java to return a super fast copy of a collection instance, this is good/normal code.
Can someone explain what he is talking about with FizzBuzz and a map? I understand a map as either a hashmap like a typical Javascript object or the Array prototype function map where you iterate an array an pass a function to run that takes each item in the array as an argument. I was trying to look up solutions to FizzBuzz that use a map (or Array.map) and I can't seem to figure out how that would make it more extensible or scalable that using if statements.
You are overthinking it! I initially thought the same thing but realized there are referring to "map" ( iterate n times and transform each value ). FizzBuzz is so Trivial that it makes it difficult!
Its the hashmap one. It seems overkill if you're only dealing with 2 or 3 replacements, but it shows that you could design a routine that might take maybe 30 replacements if you wanted without having to write a giant stack of if/else. Of course you can do that with just a bunch of single ifs (not else ifs) as long as you're careful to only print a newline at the end of them all, but the next question (to drive you to the "correct" answer) would be asking how the replacements could be configured / passed into the method externally rather than hardcoded. If they push you to the map solution (one way or the other), and you're sufficiently familiar with your language's data structures to know how to deal with it (because they'll obviously tell you to suggest an answer yourself!), you can ask if the order of the words matters. In most languages the basic map structure is unordered and since that's (usually) not the goal of the exercise the interviewer might not have been thinking about it (not that they wouldn't understand the question of course, just that it might not have been in their head at the time so bringing it up might show an extra layer of thought about the problem). Of course FizzBuzz is so well known its unlikely they'll push all that hard. If its used at all anymore, it'll just be as a basic filter problem and they'll focus on something more relevant (and less likely to have just been memorized from any of the million examples online).
@@TeslaPixel Uhh not much, I suppose. That wasn't really in the OP's question though. I was mostly distinguishing a hashmap data structure (which probably wouldn't be any better than the array of pairs) from a functional-style map() method (which wouldn't really do what's needed.. of course if you had a list of numbers you could map() them using a map :D).
About sentered code - it is actually a thing that was popular back in the days where ide was not common an people programmed in simple text editors. Ive seen that myself but aside from how it looks it was pretty comfortable to read and there was no errors.
9:19 :D i don't get why you would ask someone about maps with this BEGINNER exercise. Even if you do, it should like: can we improve that code to accept more that 2 numbers for checking (something like that).
Yeah this annoyed me too. The screenshot literally shows the correct way to write a standard fizzbuzz function for numbers 1-100; from the code it's immediately obvious what the function does - it's not badly written at all. Part of programming is realising when writing something simple is enough to get the job done; as soon as you start introducing abstraction, maps, 'future proofing' when asked a simple fizzbuzz question you just come off as a smartass. It's a function used to teach absolute beginners for-loops and control-flow logic. In fact, if we want to be pedantic, writing this function in a 'smart' way will often just make it slower, since the compiler won't be able to apply the same optimizations it otherwise can.
3:25 I actually have to do that kind of bullshit because of stupid Sonarqube configurations that don't let me reuse the same literal value more than once...
True. It is interesting because sometimes it can go the opposite way, although simplicity is usually compressed complexity. Think of a painting that is consistent in color and you can see clearly what it is. Then think of a painting that is abstract, like different shapes and colors. It can be a design and style choice, but, I do agree that simplifying things is the idea of efficiency.
9:36 can smeone explain what he is talking about? As far as I am aware, you still need to use a number of if statements... Like the only thing I can think of that he might be talking about is creating an empty output string and then concatenating it with "Fizz" on 3 "Buzz" on 5 and "Bazz" on 7, which still requires 3 if statements. What does he mean by "anyting better"?
You can map an integer to a string. And then when iterating over numbers you additionally iterate over the map keys. This approach is slower but more "extensible". Slower because you have to jump around memory and cause a shitton of cache misses. Basically this is a shit question that depends on the interviewers interpretation on what is an "optimal" solution
You only "need" one if statement. A dictionary is a kind of map. eg condition = {"Fizz":3, "Buzz":5} for i in range(1,101): print( ''.join(k for k, v in condition.items() if i%v==0) or str(i) ) You dont even really need the if statement (in Python, true == 1 and false ==0 and you can multiply strings by int). Below works too. condition = {"Fizz":3, "Buzz":5} for i in range(1,101): print( ''.join(k*(i%v==0) for k, v in condition.items()) or str(i) )
Yeah, this got me stumbled too. But apparently, he says "..what the maP is". Tbh, I don't know where map is useful in FizzBuzz, because all languages I know doesn't have map function in standard libs 😄.
i was fixing some strange proxy problem, where non dynamic images caused problems... yeah, 10 levels of nesting with structures with a switch in a switch in a for loop, that exits after the first itteration inside a switch inside a lot of ifs... calling random functions with about the same level of nesting... yeah, in the end the solution was to just put other image urls in the db and somehow the server to which the proxy pointed was able to get those images from the cdn and return it... so proxy pointing to a image cdn, that just calls the url from our real cdn... yeah... because some 3rd parties are not following standards, we sill have to keep the legacy app running... and now we have to port it (aka i ported it and we have to test some things)
I had to spend probably an extra week of effort debugging an application on a customer environment the dev team doesn't have access to because the application is riddled with exception catches that throw new exceptions everywhere so you can never figure out the full story and even with full server logs w/ annotated context and testing results the dev team isn't always sure what happened. I kept mentioning that it was unfortunate I couldn't know what the error actually was because of it. But instead of getting better, there were more catch throw new added and added. I just couldn't even anymore. Just couldn't even.
Here's my Fizzbuzz in Haskell I made while trying out Haskell, I'm excluding the tests, test harness, main IO function and combining it all into one file. I wanted to have a ruleset file that was the only thing you needed to change to add more rules like is commonly asked in the FizzBuzz toy problem. import Data.Foldable import Data.Maybe type FizzRule = Int -> Maybe String fizz :: FizzRule fizz = rule 3 "Fizz" buzz :: FizzRule buzz = rule 5 "Buzz" foo :: FizzRule foo = rule 7 "Foo" bar :: FizzRule bar = rule 11 "Bar" baz :: FizzRule baz = rule 13 "Baz" rule :: Int -> String -> FizzRule rule n m i = case i `mod` n of 0 -> Just m _ -> Nothing fizzBuzz :: [FizzRule] -> [Int] -> [String] fizzBuzz rules = map f where f i = fromMaybe (show i) (ruleset i) ruleset = fold rules
1:34 I have this in my code 😃 though I would say it's the most natural solution as I am writting a custom language compiler and when an error is thrown during macro expansion I want to log the entire macro expansion chain. (Like "missing semicolon", "note: in expansion of macro macro_2!()", "note: in expansion of macro macro_1!()" ...)
I was so confused about how FizzBuzz can be done with a map. And after giving up and looking it up. It's actually NOT A MAP. Okay, it's specifically not a hash map. It gets converted to an array of conditions and each number is run through the array to see if it matches one of those conditions.
using map with a json object makes the code scalable so no matter how many different things you put in it will work without major code changing. Its better to have one additional variable that holds the dictionary than having to add a new if statement each time you need to add a new thing.
Well.. I don't think it needs to be a map necessarily, but you definitely shouldn't be doing if(i%3 == 0 && i%5 ==0) and the like (unless you're absolutely certain that those values will never change and won't need to add more values in the future). I'd personally just write it as something like this: result = "" if(i%3==0) result += "Fizz" if(i%5==0) result += "Buzz" if(result == "") console.log(i) else console.log(result) You could use a map if you wanted to, but I don't think it would really improve maintainability or performance at all - adding an extra if statement isn't going to be any more complicated than adding another element to a map. The real problem with the original solution is that it's trying to check for every combination instead of just checking each individual condition and then concatenating the strings, which will quickly get ridiculous if you have more than 2 conditions to check for.
The "catch Exception(err) throw new Exception(err)" has layers to it man... not least of which is the mystery of what's going on before and after it. Look closely at the nesting. This is INSIDE of some kind of nested loop. And not at the end. I know not what crime was committed up above this one, but it was so bad the author decided outright murder was the only way out alive.
1:35 this is a valid solution when you need to strip everything but the message string to avoid leaking sensitive data. It would be better to rewrite the error though. Bandaid foxes cost more in the longun.
I agree a lot of so-called geniuses to speak in a certain way that makes them seem smarter than they really are... Neil deGrasse Tyson being the main person I think about when I think about people who everybody thinks is a genius but just seems to be very assertive and talk in a very specific way.
From what I've read of N. D. Tyson, he's a lot smarter than you and I in astrophysics. But coders (I'm not one, at least one professionally) often do clever stuff like x += 1; rather than x = x + 1; just to show off methinks.
@@raylopez99 "But coders (I'm not one, at least one professionally) often do clever stuff like x += 1; rather than x = x + 1; just to show off methinks." bruh
@@raylopez99 a better example that is far less clear is in something like C, combining iteration and dereferencing in to an already dense bit of code. it's unnecessary and poorly breaks down the solution in to its meaningful parts.
it's ok for FizzBuzz as a kid's game, but not as a programming exercise. If i tell you to add 20 new rules or 100 or 1000. If statements wouldn't cut it. Your code should be easy to modify and easy to scale up.
@@tapwater424 try to add 20 more words. You would need to add 40 lines of code. But if you implement a ruleset - you'd need to add only those 20 words and 20 numbers. Try to add 100,000 new words - it's not easy to add so many if statements, unless you use some form of meta-programming. With ruleset - you can fill and empty it with code - so there's a very little work required to handle that many cases. Can you make it work if all words in a separate file supplied by user? Or you need to count sum of first 1000 numbers. Can you make any change like this change efficiently without wasting much of your limited thought space and your time? A lot of if-statements are only good if you're 100% sure the code will never have to change, but in a real word - most of the code has to change and often scale.
@@dolorsitametblue It's trivial to change later if it turns out you need 10000 cases. But you don't and you never will, and it's gonna be easier to read the code if it's just a simple chain of else if statements. Not to mention that it's trivial to duplicate one of the if..else lines with most editors. It's also more performant, which matters at scale.
My take is that it makes it easier for you to add and remove as many entries (buzzes, fuzzes, woofs, meows and so on) as you want. I've just past another comment giving a sample in js like this: { 3: "Buzz", 5: "Fuzz" }
@@Caue113_ doing `else if n % 5 == 0 ...` is as many lines as doing `5: "fuzz"`, except that the latter solution is less obvious at a first glance and way less performant.
@@tapwater424lost a bit of context as its been quite some time lol. But if you are just hacking your way through to finish something asap, it's fine. The map usage is there to make it easier to understand and flexible do add/remove whatever text, number or any symbol.
@@tapwater424 flexibility doesn't have much to do with line count that much. It is ofc way better if we shrink it as much as we can without affecting readability. The point that the map makes is to separate data from code. So if you get such a big logic behind and a very large number of "data" you would want to classify, a database may be a best tool to organize it. This as well the use of map (hashmap to ease searching the data structure) get you an O(1) read access. That means, whatever the result of my "n % i" it will generate an integer number, which can be a key to an associative array. Now, this kind of iteration logic could be more complex and take maybe 20, 40, 50 or even 100 lines of code to tackle this classification plus edge cases. But now i could indefinitely expand the data table, and even better if I as a the programmer let data scietists regulate their own ways of dealing with data and not worry much at all.
const sentence1Array = ["There", "is", "a", "big", "problem", "with", "this", "video"]; const sentence2Array = ["It", "was", "too", "short"]; console.log(sentence1Array[0]); console.log(sentence1Array[1]); console.log(sentence1Array[2]); console.log(sentence1Array[3]); console.log(sentence1Array[4]); console.log(sentence1Array[5]); console.log(sentence1Array[6]); console.log(sentence1Array[7]); console.log(sentence2Array[0]); console.log(sentence2Array[1]); console.log(sentence2Array[2]); console.log(sentence2Array[3]); I had to fight with Chat-GPT, more than 5 prompts to force it to write the code in this way. But it didn't complain about writing it in JavaScript
I just paused the video at 3:20 and didn't realize for a full minute, because I was thinking it was already accidentally paused and tried to "unpause" it.
Uuhh, kinda in that first situation right now. Other than throwing a NEW exception, what is wrong with it if I absolutely have to handle the error (as in a specific error that might be thrown there) higher up the call chain?
You are buying nothing by doing that as its still the callers problem. You've added no information and added noise. If you were translating it to a RUNTIME exception or adding some contextual information to the error string it'd be potentially useful.
@@DagarCoH Sorry, i meant 'you' as anyone doing what was shown in the video :) It can be very helpful to report on other state at the time of the error for logging to debug it, even if you can't recover.
@@DagarCoH As long as you're doing _something,_ its justifiable (well assuming the thing you're doing is not in itself useless of course). Wrapping an exception to change its type or provide additional context is an extremely common thing to do. Its the rethrowing of the same exception without taking any other actions that's pointless. Actually as written, its somewhat dumber than pointless - its taking a potentially typed exception and wrapping it in a generic Exception. Just as useless as rethrowing the same one, but with the added bonus of shunting the actual exception information (including the exception message) one level down the cause/innerException chain and making it that much harder to find the real cause within the stack trace. Someone higher in the comments suggested this might be done to intentionally blitz the stack trace in case it contained sensitive information. That's a valid thing to do (though not really the right way to do it), but the code in the video doesn't even accomplish that task in any meaningful way: - If the logger fails to dig into the cause/innerException chain, then you've not only lost the original stack trace but also the error message, making the log message entirely useless. - If it does dig into the cause/innerException chain then you've accomplished nothing other than to make your log output longer.
Fizzbuzz specifies a relationship between numbers and strings. You can encode this relationship in an extensible and clear way with a map. For few key value pairs (two or three) using conditionals isn't two bad, but as you add more cases, it becomes more repetitive and noisy. Also, if you don't concatenate your strings and instead use separate conditions for combinations of base cases, combinatorial explosion will be your downfall, because the amount of ways to combine the factors will grow very fast. Using a map and concatenation keeps the solution logically the same across any number of factors and you only need to change the key value pairs you register in your map.
@@ccgarciab Thanks, really appreciate the elaborate explanation, but I'm still not sure how an implementation would look. Would it be too much to ask for a code example, a GitHub Gist or something similar? I'm a self-taught web developer, and only just started learning about CS, data structures and algorithms, but my guess is a map is like a list of tuples (Python) or an associative array (PHP) or even an array of arrays (JS) you'd loop over? I have tried to Google it first, but I only get FizzBuzz solutions using the JavaScript map method.
@@MichaelLazarski Thanks! I actually posted a link to a Gist with one of my solutions, but it looks like it got deleted or I can't share links. This is what I came up with after finding docs on JavaScript Maps: const fizzBuzzMap = new Map(); fizzBuzzMap.set('Fizz', 3); fizzBuzzMap.set('Buzz', 5); fizzBuzzMap.set('FizzBuzz', 15); const fizzBuzz = (n) => { let result = ''; fizzBuzzMap.forEach((value, key) => { if (n % value === 0) { result += key; } }); return result || n; };
3:40. I can't wait to see that applied to public defaultValue = defaultTrue; public pointlessClassPropertyThatOnlyNeedsToBeInScopeForASingleFunction = defaultValue;
1:32 I reviewed way worse code. Like a big ass several thousands lines Java ETL that would try/catch every single NPE in its own block and do nothing about it. So instead of failing at the first NPE, it would continue until the end, return a status 0, except it did shit all.
so, there are some programming languages developed exclusively to least ammount of characters code challenges, so they have some pretty complex semantics.
Oh that makes sense, and fits with my perspective that I'm an absolute clown... 0:57 5:02 as an interjection to the fact that print takes multiple arguments, that is fine, and any other context... Actually, I would argue that using non-branching code would be better. [To implement fizzbuzz]
The only reason why I don't fuck up with .sort() still to this day despite knowing this is that I implemented an O(n) heap-sort variant in the codebase and calling that anyways :D :D :D
I used to be really frustrated with how difficult to understand academic papers are, but after gaining enough knowledge, I'm now a little more sympathetic - it's really easy to tersely express ideas with complex language, simplifying them requires a lot more effort and is almost always more verbose.
It would be nice if someone would keep a dictionary for all the field specific words that have quite precise meanings. That way ppl could reference that source instead of spending one or more paragraphs explaining a single word or notation. Or leave it as an exercise for the reader to figure out what something means.
edit: before ppl explain the obvious fighting over the meaning of words this would produce, I know but a potato can dream.
It may be field specific, but I honestly rarely encounter papers, that are complicated for the sake of being complicated, as some kind of intelectual voyeurism. Most of the difficulty comes from not knowing the field, which cannot be easily overcome I'm afraid.
AI will make things so much more bearable now that no one will actually reading the papers any longer.
Stockholm syndrome let's gooo
@@rumplstiltztinkerstein it's likely that until AI is fully self-explainable and deterministic society will continue to rely on human correction and oversight at least for success critical projects
One from my brother:
Code purpose: Every time list is changed, sort list.
Problem: sorting list counts as a list change, producing infinite recursion.
Solution: catch exception when hitting max recursion depth, assume list is sorted at that point, and continue from where you left off.
As he says: "if it works, it works!"
[He did fix it the next day when he worked out the proper way to do it.]
Based
I think you need to keep an eye on him. We should be scared of people like that
Can't he add new items with binary search and escape sorting each time?
Just bisect the new items in
This sounds like Blazor callbacks to be honest.
5:31 For those wondering, this is Minecraft enchanting table language (aka Standard Galactic alphabet), which is actually not a language but just a font that looks all funky
i hate that it's known as the minecraft language, rather than the commander keen language. but i guess it's nice that some people might be led to discover commander keen throught it.
I feel like that one is only funny if you a) don't know about Unicode or b) get the reference.
@@Jalae Oh yeah, that guy you kill in Doom
i wrote a JS "translator" for this once - it's actually comprised of unicode. what's worse is some ASCII chars actually are represented by multiple SGA chars which broke my poor virgin JS dev soul
@@fwfy_ Oh, man! Multi byte character translations are the worst! I would have that, too.
Glad you enjoyed this 🤣. There are so many versions of this now and I'm so glad you picked mine! And sorry about the video quality 😅
Oh really? I've only seens yours never search them up tho
8:47" if(true == false)" that is some interesting fucking code there.
I’ve done it ¯\_(ツ)_/¯
Back before I’d set my comment-block to the best ever keyboard shortcut (Shift+Alt+A)
Protip: you can set a block comment shortcut in SSMS.
Sadtip: you cannot use the same shortcut to block uncomment :(
Mildtip:
• (Shift+Alt+A)->block comment
• (Ctrl+Shift+Alt+A)->block uncomment
i do that all the time in unity, all it does is ignore the function until i finish it so i can run the game, if that is at the end a jususst use return but some ides complain that there is code after the return
in java, you could change false to returning always true (and vice versa) via reflection, so this if block could actually be executed. ofc pointless, just saying for funsies
@@timber2leasecan you show an example of
would be useful to know if someone's screwing with boolean logic. some people have evil coworkers which will slightly tweak axioms
1:34 I actually did that recently. The stack trace sometimes contained personally identifiable information, so I caught and rethrew the error to get rid of it in our logs.
You better have commented that so the next person around doesn't think you're a moron.
Then you better have had a comment explaining why you would want to be doing that.
@@calebvear7381 I did. It was several lines long actually.
@@calebvear7381 Or, you name the Exception you catch badBoyWhoKnowsTooMuch and you name the one you throw niceGentleLadWithNoSecrets
The real solutions would be to fix the error so that it doesn't contain sensitive information
7:13 When the developer says that they code 1000 lines of code a day
This shit is horrendous
Dude I laughed at this for two minutes 😂
I literally had seen code from a colleague with constants like this:
int OneSecondWaitTimeout = 1;
int TwoSecondWaitTimeout = 2;
int FiveThousandMillisecondsTimeout = 5000;
Not a joke, it exists and everytime I review code from this guy, I die inside.
I take it this was used one time in one file, but if any one of these were used in ~100 places across several files, it makes sense to capture it in a variable.
@@Honken
How does it make any sense to store constant integers in local variables?
@@Asto508 Not local; global. That's what I meant with "100 places across several files".
Magic strings and numbers are a major PITA. It's better to group them in one place and refer to them via constants or enums.
If by your post you meant that your colleague keeps them _in one scope_ then yeah, that's dumb AF and I feel your pain; I get those as well.
```
const isLoggedIn = user.logged_in
if (isLoggedIn) {
...
}
```
_fukme_
@@Honken Well, if the constants are actually some very important number, then I can see your point, but we are literally talking about "1" or "2" in constants named "One" and "Two".
@@Asto508 The same principle still applies; if they are used hundreds of times, by having them constant you have one uniform value instead of hundreds of arbitrary values, hence the word 'constant'.
If we need to change TIMEOUT from 2.0 to 5.0, that's a one line change.
If we have to dig through tens of thousands of lines of code and find every `timeDiff.Seconds >= 2.0`, we will be wasting a lot of time and run the very palpable risk of missing one and heisenbug ourselves into pager duty on Christmas.
As dumb as it sounds, having a constant/enum called One which is bound to the integer 1, if the references to that number is high, it's an investment well made.
I've seen this one java class that had a 6,500 line method with 5 layers of inheritance. Stuck right in the middle of the method were these two massive nested if blocks where they both were ~450 lines of if, else if, else crap.
Best part was the second of the two if blocks was a copy and paste of the first with one comment saying "don't delete this because for some reason the code won't work without it," and you know what that person was right!
On my first ever project that wasn't trivial I had a similar situation where I needed to add else if instead of else or the code didn't work. To this day I don't know why that was the case as it was supposed to be a boolean condition. Anyways, long ago I rewrote that entire part of my project, so I no longer have that issue.
I've led a priviledged life. The C code I work with most days is bad, but never this bad. Thank you kernel devs.
the funniest thing in java to me is to catch an IOException, just to re-throw an UncheckedIoException
That sounds reasonable, though. At least you're changing the type of the exception and giving it a new context (or, in this case, escaping the hell that is Java's checked exceptions). Throwing a play Exception is just throwing the stack track and type away.
Telling people that FizzBuzz example is war crime, is a war crime.
I mean, the whole point of FizzBuzz is to NOT do it that way, so....
@@aenguswright7336 I thought the point of fizzbuzz is the modulo operator? Unless you mean you're always meant to use string concatenation?
@@aenguswright7336 Tell us, without searching it up, why it's a bad idea to use if..else if..else for fizzbuzz
@@aenguswright7336 What do you mean? This is a very common way to solve it. KISS, keep it simple stupid. Why would you overcomplicate it for no reason?
@@aenguswright7336 if-else is actually faster
there's no reason to use a map unless you have a ton of different conditions
Who took pictures of my code?
Microsoft recall beta.
5:42 Not only kids use Scratch, also some grown-ups that enjoy a challenge. There's a full RISC-V emulator written in Scratch that runs a tiny Linux distro. And when compiled to JS it is actually acceptably fast with a boot-up time of ~20s. On vanilla Scratch it takes longer than an hour to boot at which point I just cancelled it.
„A physicist tries to make it simple.“
The guy has never seen code written by a physicist
For me, codes written by physicists are way more transparent than those written by professional programmers. Perhaps because I am a physicist myself.
9:05 Just for fun I just challenged myself to do a FizzBuzz and I used an object with numbers as keys and the wanted strings as the values, iterating over the wanted number range and at each iteration iterating over the previously-defined object and checking if i is cleanly divisible by the number and if yes adding its associated string to an array. At the end of the iteration step I check if the aforementioned array is empty. If yes, I output the number and if not I join the array elements together with an empty string. Adding seven for "Bazz" was as easy as defining the object's key "7" as "Bazz".
6:38 Experts, please explain to me the difference between a Git rainforest and a primitive Git jungle. What are the most toxic bugs that can be found in there?
I think a git bamboo forest is better. No merging ever
I don't know if this is right, but for the FizzBuzz question, I would have done it this way:
conditions = {3: "Fizz", 5: "Buzz", 7: "Bazz"}
for i in range(1, 101):
result = ''.join(v for k, v in conditions.items() if i % k == 0) or str(i)
print(result)
Not going to check it, but looks right to me. Maybe add a length variable
I used to do it branchless, thanks to bad habits i picked up from codeingame:
for i in range(1,101):
print( ("Fizz"*(i%3 ==0) + "Buzz"*(i%5 ==0)) or i )
There are so many ways to do it.
Recursion:
def fizzbuzz(i=0):
if i==100:
return
print( ("Fizz"*(i%3 ==0) + "Buzz"*(i%5 ==0)) or i )
return fizzbuzz(i+1)
Awful hashes:
fizz = { str(n*3) for n in range(100//3) }
buzz = { str(n*5) for n in range(100//5 }
for i in range(1,101):
print( fizz[i]+buzz[i] or i )
Generators too:
fizzbuzzgen = ( ("Fizz"*(i%3 ==0) + "Buzz"*(i%5 ==0)) or i for i in range(1,101))
while fizzbuzzgen:
print(next(fizzbuzzgen))
Without modulus and division:
fiz = 0
buz = 0
for i in range(1,101):
fiz+=1
buz+=1
print(("Fizz"*(fiz==3) +"Buzz"*(buz==5)) or i)
fiz = fiz*(fiz!=3)
buz = buz*(buz!=5)
Hell even pure CSS (with LOADS of empty divs in html):
.fizz-buzz {
counter-reset: fizzbuzz;
}
.fizz-buzz > div::before {
content: counter(fizzbuzz);
counter-increment: fizzbuzz;
}
.fizz-buzz > div:nth-of-type(3n+3)::before {
content: "Fizz";
}
.fizz-buzz > div:nth-of-type(5n+5)::before {
content: "Buzz";
}
.fizz-buzz > div:nth-of-type(3n+3):nth-of-type(5n+5)::before {
content: "FizzBuzz";
}
looks good
the thing is, the 'if/else' fizzbuzz solution is usually the most performant. It's just not scalable at all. Also if you add 'bazz' as 7 then would you also print 'fizzbuzzbazz' when the number is divisible by all of them?
yes, but that only occurs at 105 at the first time (3*5*7), so you would have to change the upper limit of the range for this to happen at least once
It’s not the most performant. Use counters instead, which reset on hitting 3 and 5 and you remove %. Optimize it further and populate an array[n=smallest divisible number=3*5] with answers and write to output as many times as needed.
Prime's reactions are the funniest
:)
@@ThePrimeTimeagen its cute and funny, cunny
@@PragandSens There's a time and place for everything, and prime correction is not yet meant to be 😭
Nobody press another like. This is where it should be.
I entered a twitch stream once. They unironically used a cursive font. i asked them about it, wished them a good day and left.
Catching and then rethrowing immediately is useful when you need a debugger trap because breaking on exception sometimes destroys the callstack legibility, I'm looking at you javascript. And then you forget it and push it to production.
Language-specific quirks are understandable but I think this is Java where that doesn't make sense
In Python raise Exception() from e is legit for catching whole stack trace for debugging purpose :)
In the Java case, the debugger trap is useful as setting a breakpoint at the end of a function doesn't get triggered if the stack is being jumped/unwound. There may be advanced debugger features that can do this, but its much easier to combine basic debugger functionality with basic code and set a breakpoint on that line so you can examine what's going on as the exception is being thrown.
A very similar (but not exact) reason to do this is if the caught exception is checked and you're just rethrowing an unchecked, or a different wrapped checked (ugh) exception.
@@drewbabe
If it hasn't changed it's necessary in Java to catch exceptions (elsewise the code will not compile), if you can't handle them you have to rethrow them.
Thus the shown code is the only valid way in Java to escalate the exception upwards into runtime.
It's not cringe in anyway, not every exception can be handled by a program, but needing to handle all exceptions leads to more safe code (defensive programming).
I mean Rust does pretty much the same thing with an onEvent function instead of a catch block and people praise rust for this.
Just because it's older way, doesn't make it worse.
@@MrDavibu I don't see how putting it in a try/catch block would change anything in Java. I don't know if it was ever different, but when I've worked with Java the way it works is that a function can't throw an exception unless you include "throws Exception" (or some subclass of Exception) as part of the function declaration, and if you do have that included as part of the function declaration then you don't need to include a try/catch block even if something within that function throws an exception.
Solving fizzbuzz with map instead of string concat is like mowing lawns with artillery.
(Thumbnail)
"I destroyed the error to create the error"
When I wrote fizzbuzz for the first time I did it in Python in a way that you could pass the fizzbuzz function a dictionary where the keys are numbers and the values the strings to replace them with, so you could call it with {3: "fizz", 5: "buzz"} or {3: "fizz", 5: "buzz", 7: "bazz"} or whatever you like, with pretty much as big a dictionary as you wanted.
Ah, the "replacing combinational logic with ROM" solution, software edition.
@@henry_tsai I think I described it poorly. You don't pass a dictionary with all the numbers. If you pass just {3: "fizz", 5: "buzz"} it will automatically replace all multiples of just 3 with fizz, all multiples of just 5 with buzz and all multiples of 15 with fizzbuzz. If you pass {3: "fizz", 5: "buzz", 7: "bazz"} it will additionally replace all multiples of 21 with fizzbazz, all multiples of 35 with buzzbazz and all multiples of 105 with fizzbuzzbazz. That is, assuming I added a maximum number parameter to allow it to output more than 100 numbers, which I don't remember if I did or not, and I don't know if still have the original code I wrote.
that's what he said in the video, use a map.
To be fair to academics, when you're dealing with complex topics you need specialist language for it.
At about 7:40 into the video... I've heard of, seen and have unrolled loops for efficiency reasons to minimize the branch predictions, etc. Yet I don't think I've ever heard of or seen unraveling operations that can be calculated by simple iterators. I'd hate to have to be the branch predictor on the machine that has to run this code.
Sometimes at work (in Go) we write functions that take a pointer to a boolean as a parameter, usually for a simple filter that has three states (eg: when requesting customer list get free users / premium users / all users). Certain higher level functions always need a particular list, but you can't just pass true because it needs to be a pointer, so I call it like this:
true := true
myFunction( &true )
"If it's stupid but it works, it's not stupid." (/s)
One that always gets me:
```
if condition
return true
else
return false
```
Or one where items were deleted from a collection in a set of nested loops and checks, e.g.
```
while true {
for index in range {
if (range[index] == itemToDelete) {
range = range[0..index-1] + range[index..range.size]
found = true
}
}
if found break
}
```
There are so many better options one can choose. One, assuming no need to preserve order or immutability is to reverse the iteration order and swap the found item with the last [unmatched] index and then just trim the collection to the new size.
You can rewrite the first one as "return condition ? True :False"
@@hbrg9173 Or just "return condition", it's clearly already Boolean.
@@TheAndreArtus it could be a truthy value
@@Nathan-pl2cf You can still return directly with a double negation (e.g. JS) or type cast (e.g Python). If you can branch on a condition then you can also directly return a boolean representation thereof (true|false; 1|0; etc.) in most common languages. Personally I try to dispense with weak notions of type as soon as possible as these, in my opinion, are too frequently a source of bugs.
@@TheAndreArtus I agree, just wanted to point out that they weren't entirely wrong, depending on the language anyways. I would probably go with explicit casting over the ternary though.
For the FizzBuzz stuff, use a map with numeric keys and what should be printed. Use % key == 0, add value to variable and print at the end, printing the number if variable is empty.
You're welcome.
What do you mean by " % key == 0"? You mean iterate over the key values and check if whatever number you have `% key` is 0? Then what's the point of having a map in the first place?
you're saying something like the following (don't mind the variable names :| ):
```rs
pub fn fizzbuzz(input: usize) {
let map = [
(3, "Fizz"),
(5, "Buzz"),
(7, "Baz")
];
let res = map
.iter()
.filter(|(k, _)| input % k == 0)
.map(|(_, v)| v)
.fold(String::new(), |acc, e| acc + e)
;
println!("{}",
if !res.is_empty() { res }
else { input.to_string() }
);
}
```
?
@@MH_VOID Yeah, that seems correct to me. That way you only need to adjust the data rather than the "business logic".
@@GiletteRazorsharp See the reply from MH_VOID. The point is to not have to adjust the logic, only the data.
@@CottidaeSEA sure, but MH_VOID isn't using a map. That's just an array of tuples. Still, why would that be any better or worse than having just more if statements (presuming you do string concatenation)? I'd argue it's less readable unless you're getting into many more than 4 or 5 branches.
I love that “Bustin’” is on your watch list 😂
I think what he means with fizzbuzz and map and adding a 7 for example would be this:
const condition = { 3: "Fizz", 5: "Buzz", 7: "Prime" };
for (var i = 1; i i % key === 0 ? value : "")
.join("");
if (!answer) answer = i;
console.log(answer);
}
That example is relying on JS coercing "key" to a number in the modulo expression. It does work, but in TS you'd want probably want `i % +key`
why are you using var in 2023, dude, ew
@@twothreeoneoneseventwoonefour5 haha I didn't even notice that
I have also done it in one liner (kind of):
const conditions = { 3: "fizz", 5: "buzz", 7: "prime" };
for (let i = 1; i
i % +key === 0 ? conditions[key] : ""
)
);
console.log(line);
}
Or better to use an actual map here:
const conditions = new Map([
[3, "Fizz"],
[5, "Buzz"],
[7, "Prime"],
]);
for (let i = 1; i
@@twothreeoneoneseventwoonefour5 This is something i wrote quickly in the console and if its let or var here is so unimportant :D
There are 1000 ways of solving this.
Yesterday i was refactorig some code written by a collegue and i found this gem.
$files = [ ]
foreach ($media_files as $file){
$files [] = $file;
}
return $files;
Also the most evil definition of true/false ive ever seen is
#define true (rand() % 2)
#define false (rand() % 2)
Making a copy of a list to avoid leaking internal state or reference issues has many valid uses. You probably broke your colleagues code and caused a disaster due to naivety.
@@gregorymorse8423 no, it everything works perfectly fine.
@@gregorymorse8423 $files = $media_files copies the "array" in php
@@gregorymorse8423I was about to say that, unless php has some function like Java to return a super fast copy of a collection instance, this is good/normal code.
Works 1/4 of the time every time
I did not want to be the one to say this, and yes I am an idiot, but the UI in templeOS is the definition of complex.
Make no mistake - Terry Davis was a human Cypher
reported for terrorism and misinformation
Can someone explain what he is talking about with FizzBuzz and a map? I understand a map as either a hashmap like a typical Javascript object or the Array prototype function map where you iterate an array an pass a function to run that takes each item in the array as an argument. I was trying to look up solutions to FizzBuzz that use a map (or Array.map) and I can't seem to figure out how that would make it more extensible or scalable that using if statements.
You are overthinking it! I initially thought the same thing but realized there are referring to "map" ( iterate n times and transform each value ). FizzBuzz is so Trivial that it makes it difficult!
Its the hashmap one. It seems overkill if you're only dealing with 2 or 3 replacements, but it shows that you could design a routine that might take maybe 30 replacements if you wanted without having to write a giant stack of if/else.
Of course you can do that with just a bunch of single ifs (not else ifs) as long as you're careful to only print a newline at the end of them all, but the next question (to drive you to the "correct" answer) would be asking how the replacements could be configured / passed into the method externally rather than hardcoded.
If they push you to the map solution (one way or the other), and you're sufficiently familiar with your language's data structures to know how to deal with it (because they'll obviously tell you to suggest an answer yourself!), you can ask if the order of the words matters. In most languages the basic map structure is unordered and since that's (usually) not the goal of the exercise the interviewer might not have been thinking about it (not that they wouldn't understand the question of course, just that it might not have been in their head at the time so bringing it up might show an extra layer of thought about the problem).
Of course FizzBuzz is so well known its unlikely they'll push all that hard. If its used at all anymore, it'll just be as a basic filter problem and they'll focus on something more relevant (and less likely to have just been memorized from any of the million examples online).
@@altragwhat does a map give you over an array of pairs?
@@TeslaPixel Uhh not much, I suppose. That wasn't really in the OP's question though. I was mostly distinguishing a hashmap data structure (which probably wouldn't be any better than the array of pairs) from a functional-style map() method (which wouldn't really do what's needed.. of course if you had a list of numbers you could map() them using a map :D).
About sentered code - it is actually a thing that was popular back in the days where ide was not common an people programmed in simple text editors. Ive seen that myself but aside from how it looks it was pretty comfortable to read and there was no errors.
This dinosaur has never heard of Python lol.
9:19 :D i don't get why you would ask someone about maps with this BEGINNER exercise.
Even if you do, it should like: can we improve that code to accept more that 2 numbers for checking (something like that).
Yeah this annoyed me too. The screenshot literally shows the correct way to write a standard fizzbuzz function for numbers 1-100; from the code it's immediately obvious what the function does - it's not badly written at all. Part of programming is realising when writing something simple is enough to get the job done; as soon as you start introducing abstraction, maps, 'future proofing' when asked a simple fizzbuzz question you just come off as a smartass. It's a function used to teach absolute beginners for-loops and control-flow logic. In fact, if we want to be pedantic, writing this function in a 'smart' way will often just make it slower, since the compiler won't be able to apply the same optimizations it otherwise can.
3:25 I actually have to do that kind of bullshit because of stupid Sonarqube configurations that don't let me reuse the same literal value more than once...
True. It is interesting because sometimes it can go the opposite way, although simplicity is usually compressed complexity. Think of a painting that is consistent in color and you can see clearly what it is. Then think of a painting that is abstract, like different shapes and colors. It can be a design and style choice, but, I do agree that simplifying things is the idea of efficiency.
9:36 can smeone explain what he is talking about? As far as I am aware, you still need to use a number of if statements...
Like the only thing I can think of that he might be talking about is creating an empty output string and then concatenating it with "Fizz" on 3 "Buzz" on 5 and "Bazz" on 7, which still requires 3 if statements.
What does he mean by "anyting better"?
You can map an integer to a string. And then when iterating over numbers you additionally iterate over the map keys. This approach is slower but more "extensible". Slower because you have to jump around memory and cause a shitton of cache misses. Basically this is a shit question that depends on the interviewers interpretation on what is an "optimal" solution
You only "need" one if statement. A dictionary is a kind of map. eg
condition = {"Fizz":3, "Buzz":5}
for i in range(1,101):
print( ''.join(k for k, v in condition.items() if i%v==0) or str(i) )
You dont even really need the if statement (in Python, true == 1 and false ==0 and you can multiply strings by int). Below works too.
condition = {"Fizz":3, "Buzz":5}
for i in range(1,101):
print( ''.join(k*(i%v==0) for k, v in condition.items()) or str(i) )
Evaluating one's mathmatical ability with FizzBuzz is like judging a tree by its walking capabilties
Yeah, this got me stumbled too. But apparently, he says "..what the maP is".
Tbh, I don't know where map is useful in FizzBuzz, because all languages I know doesn't have map function in standard libs 😄.
@@dolorsitametblue but map isn't a function is a data structure.
@@dolorsitametblue he means a dictionary or whatever you want to call a key value pair data structure
It's literally not about math lol
@@raz1572 a map is a higher order function, not a key value pair data structure
All of the programmers who wrote those war crime programs have served sentence in programmers correctional facility.
i was fixing some strange proxy problem, where non dynamic images caused problems... yeah, 10 levels of nesting with structures with a switch in a switch in a for loop, that exits after the first itteration inside a switch inside a lot of ifs... calling random functions with about the same level of nesting... yeah, in the end the solution was to just put other image urls in the db and somehow the server to which the proxy pointed was able to get those images from the cdn and return it... so proxy pointing to a image cdn, that just calls the url from our real cdn... yeah... because some 3rd parties are not following standards, we sill have to keep the legacy app running... and now we have to port it (aka i ported it and we have to test some things)
I had to spend probably an extra week of effort debugging an application on a customer environment the dev team doesn't have access to because the application is riddled with exception catches that throw new exceptions everywhere so you can never figure out the full story and even with full server logs w/ annotated context and testing results the dev team isn't always sure what happened.
I kept mentioning that it was unfortunate I couldn't know what the error actually was because of it. But instead of getting better, there were more catch throw new added and added.
I just couldn't even anymore. Just couldn't even.
Sometimes I ask myself would Terry think my code has too much voodoo.
Here's my Fizzbuzz in Haskell I made while trying out Haskell, I'm excluding the tests, test harness, main IO function and combining it all into one file. I wanted to have a ruleset file that was the only thing you needed to change to add more rules like is commonly asked in the FizzBuzz toy problem.
import Data.Foldable
import Data.Maybe
type FizzRule = Int -> Maybe String
fizz :: FizzRule
fizz = rule 3 "Fizz"
buzz :: FizzRule
buzz = rule 5 "Buzz"
foo :: FizzRule
foo = rule 7 "Foo"
bar :: FizzRule
bar = rule 11 "Bar"
baz :: FizzRule
baz = rule 13 "Baz"
rule :: Int -> String -> FizzRule
rule n m i =
case i `mod` n of
0 -> Just m
_ -> Nothing
fizzBuzz :: [FizzRule] -> [Int] -> [String]
fizzBuzz rules = map f
where
f i = fromMaybe (show i) (ruleset i)
ruleset = fold rules
no wonder the npm package manager leftpad was faster than yours.
1:33 I did something like this in my C# .NET course where I took an IO exceptions and threw an unimplemented exception lol
7:56 JavaScript gonna JavaScript.
1:34 I have this in my code 😃 though I would say it's the most natural solution as I am writting a custom language compiler and when an error is thrown during macro expansion I want to log the entire macro expansion chain. (Like "missing semicolon", "note: in expansion of macro macro_2!()", "note: in expansion of macro macro_1!()" ...)
I was so confused about how FizzBuzz can be done with a map. And after giving up and looking it up. It's actually NOT A MAP. Okay, it's specifically not a hash map. It gets converted to an array of conditions and each number is run through the array to see if it matches one of those conditions.
Can someone explain to me how using a map makes fizzbuzz any better?
using map with a json object makes the code scalable so no matter how many different things you put in it will work without major code changing. Its better to have one additional variable that holds the dictionary than having to add a new if statement each time you need to add a new thing.
Well.. I don't think it needs to be a map necessarily, but you definitely shouldn't be doing if(i%3 == 0 && i%5 ==0) and the like (unless you're absolutely certain that those values will never change and won't need to add more values in the future).
I'd personally just write it as something like this:
result = ""
if(i%3==0) result += "Fizz"
if(i%5==0) result += "Buzz"
if(result == "") console.log(i)
else console.log(result)
You could use a map if you wanted to, but I don't think it would really improve maintainability or performance at all - adding an extra if statement isn't going to be any more complicated than adding another element to a map. The real problem with the original solution is that it's trying to check for every combination instead of just checking each individual condition and then concatenating the strings, which will quickly get ridiculous if you have more than 2 conditions to check for.
Plot twist: it wasn't a kid who made that scratch code
can't believe this has not more views, it has to be one of your best videos
5:36 discord data files?
2:00 This is a placeholder to write the exception handling routine later.
The "catch Exception(err) throw new Exception(err)" has layers to it man... not least of which is the mystery of what's going on before and after it. Look closely at the nesting. This is INSIDE of some kind of nested loop. And not at the end. I know not what crime was committed up above this one, but it was so bad the author decided outright murder was the only way out alive.
I'm lazy handling exceptions, I let the framework do it and redirect to some error page that hides the technical info
I just got it. PrimeGen looks like Ben Stiller in Dodgeball. He moonlights as a gym trainer at Globo Gym.
Teacher, why is the computer saying error everytime I run the code?
The Code:
Start() {Print("Error");}
1:35 this is a valid solution when you need to strip everything but the message string to avoid leaking sensitive data. It would be better to rewrite the error though. Bandaid foxes cost more in the longun.
3:40
CSS variables when for some reason the correct way to go about it is var(--color-red): red;
I agree a lot of so-called geniuses to speak in a certain way that makes them seem smarter than they really are... Neil deGrasse Tyson being the main person I think about when I think about people who everybody thinks is a genius but just seems to be very assertive and talk in a very specific way.
From what I've read of N. D. Tyson, he's a lot smarter than you and I in astrophysics. But coders (I'm not one, at least one professionally) often do clever stuff like x += 1; rather than x = x + 1; just to show off methinks.
@@raylopez99 "But coders (I'm not one, at least one professionally) often do clever stuff like x += 1; rather than x = x + 1; just to show off methinks."
bruh
@@raylopez99 a better example that is far less clear is in something like C, combining iteration and dereferencing in to an already dense bit of code. it's unnecessary and poorly breaks down the solution in to its meaningful parts.
@@raylopez99 Neil deGrasse Tyson is also considered as pop science by his community.
@@raylopez99 x += 1 is nothing clever. Like at all. It's just better than x = x + 1, cuz it's easier to write and to understand.
What's with the fizzbuzz? Why is it so bad to add that n % 7 there?
it's ok for FizzBuzz as a kid's game, but not as a programming exercise.
If i tell you to add 20 new rules or 100 or 1000.
If statements wouldn't cut it.
Your code should be easy to modify and easy to scale up.
@@dolorsitametblue Huh? That's obvious. My question is that what is the ideal solution then for a fizzbuzz with 1 extra clause?
@@dolorsitametblue Why are chained if statements less scaleable? They are the most performant solution and it's easy to add or remove cases.
@@tapwater424 try to add 20 more words. You would need to add 40 lines of code. But if you implement a ruleset - you'd need to add only those 20 words and 20 numbers.
Try to add 100,000 new words - it's not easy to add so many if statements, unless you use some form of meta-programming.
With ruleset - you can fill and empty it with code - so there's a very little work required to handle that many cases.
Can you make it work if all words in a separate file supplied by user? Or you need to count sum of first 1000 numbers. Can you make any change like this change efficiently without wasting much of your limited thought space and your time?
A lot of if-statements are only good if you're 100% sure the code will never have to change, but in a real word - most of the code has to change and often scale.
@@dolorsitametblue It's trivial to change later if it turns out you need 10000 cases. But you don't and you never will, and it's gonna be easier to read the code if it's just a simple chain of else if statements. Not to mention that it's trivial to duplicate one of the if..else lines with most editors. It's also more performant, which matters at scale.
I still don't know the nvim colorscheme used in the thumbnail... 😢
6:00 Meanwhile the biggest female stream was made in Scretch XD
An undergraduate here, can you explain why we should use a map for the fizzbuzz problem?
My take is that it makes it easier for you to add and remove as many entries (buzzes, fuzzes, woofs, meows and so on) as you want. I've just past another comment giving a sample in js like this:
{ 3: "Buzz",
5: "Fuzz" }
@@Caue113_ doing `else if n % 5 == 0 ...` is as many lines as doing `5: "fuzz"`, except that the latter solution is less obvious at a first glance and way less performant.
@@tapwater424lost a bit of context as its been quite some time lol. But if you are just hacking your way through to finish something asap, it's fine. The map usage is there to make it easier to understand and flexible do add/remove whatever text, number or any symbol.
@@Caue113_ but how is it more flexible? you're still adding one line per case, which is just as easy to follow if it's an `else if`
@@tapwater424 flexibility doesn't have much to do with line count that much. It is ofc way better if we shrink it as much as we can without affecting readability.
The point that the map makes is to separate data from code. So if you get such a big logic behind and a very large number of "data" you would want to classify, a database may be a best tool to organize it. This as well the use of map (hashmap to ease searching the data structure) get you an O(1) read access. That means, whatever the result of my "n % i" it will generate an integer number, which can be a key to an associative array.
Now, this kind of iteration logic could be more complex and take maybe 20, 40, 50 or even 100 lines of code to tackle this classification plus edge cases. But now i could indefinitely expand the data table, and even better if I as a the programmer let data scietists regulate their own ways of dealing with data and not worry much at all.
const sentence1Array = ["There", "is", "a", "big", "problem", "with", "this", "video"];
const sentence2Array = ["It", "was", "too", "short"];
console.log(sentence1Array[0]);
console.log(sentence1Array[1]);
console.log(sentence1Array[2]);
console.log(sentence1Array[3]);
console.log(sentence1Array[4]);
console.log(sentence1Array[5]);
console.log(sentence1Array[6]);
console.log(sentence1Array[7]);
console.log(sentence2Array[0]);
console.log(sentence2Array[1]);
console.log(sentence2Array[2]);
console.log(sentence2Array[3]);
I had to fight with Chat-GPT, more than 5 prompts to force it to write the code in this way. But it didn't complain about writing it in JavaScript
I saw the original in some image board without 240p, idk why this person made it into a 240p upload. But there you go
I just paused the video at 3:20 and didn't realize for a full minute, because I was thinking it was already accidentally paused and tried to "unpause" it.
Uuhh, kinda in that first situation right now. Other than throwing a NEW exception, what is wrong with it if I absolutely have to handle the error (as in a specific error that might be thrown there) higher up the call chain?
You are buying nothing by doing that as its still the callers problem. You've added no information and added noise. If you were translating it to a RUNTIME exception or adding some contextual information to the error string it'd be potentially useful.
@@adambickford8720 Okay, but I am adding information for logging before re-throwing the error. As far as I have seen, that is justified then.
@@DagarCoH Sorry, i meant 'you' as anyone doing what was shown in the video :) It can be very helpful to report on other state at the time of the error for logging to debug it, even if you can't recover.
@@DagarCoH As long as you're doing _something,_ its justifiable (well assuming the thing you're doing is not in itself useless of course). Wrapping an exception to change its type or provide additional context is an extremely common thing to do.
Its the rethrowing of the same exception without taking any other actions that's pointless.
Actually as written, its somewhat dumber than pointless - its taking a potentially typed exception and wrapping it in a generic Exception. Just as useless as rethrowing the same one, but with the added bonus of shunting the actual exception information (including the exception message) one level down the cause/innerException chain and making it that much harder to find the real cause within the stack trace.
Someone higher in the comments suggested this might be done to intentionally blitz the stack trace in case it contained sensitive information. That's a valid thing to do (though not really the right way to do it), but the code in the video doesn't even accomplish that task in any meaningful way:
- If the logger fails to dig into the cause/innerException chain, then you've not only lost the original stack trace but also the error message, making the log message entirely useless.
- If it does dig into the cause/innerException chain then you've accomplished nothing other than to make your log output longer.
Can someone please explain what Prime meant with using a map for FizzBuzz?
Fizzbuzz specifies a relationship between numbers and strings. You can encode this relationship in an extensible and clear way with a map. For few key value pairs (two or three) using conditionals isn't two bad, but as you add more cases, it becomes more repetitive and noisy. Also, if you don't concatenate your strings and instead use separate conditions for combinations of base cases, combinatorial explosion will be your downfall, because the amount of ways to combine the factors will grow very fast. Using a map and concatenation keeps the solution logically the same across any number of factors and you only need to change the key value pairs you register in your map.
@@ccgarciab But how would you add 'divisible by x' as key to a map?
@@ccgarciab Thanks, really appreciate the elaborate explanation, but I'm still not sure how an implementation would look. Would it be too much to ask for a code example, a GitHub Gist or something similar? I'm a self-taught web developer, and only just started learning about CS, data structures and algorithms, but my guess is a map is like a list of tuples (Python) or an associative array (PHP) or even an array of arrays (JS) you'd loop over?
I have tried to Google it first, but I only get FizzBuzz solutions using the JavaScript map method.
@@thomasdevisser
const condition = { 3: "Fizz", 5: "Buzz", 7: "Prime" };
for (var i = 1; i i % key === 0 ? value : "")
.join("");
if (!answer) answer = i;
console.log(answer);
}
@@MichaelLazarski Thanks! I actually posted a link to a Gist with one of my solutions, but it looks like it got deleted or I can't share links. This is what I came up with after finding docs on JavaScript Maps:
const fizzBuzzMap = new Map();
fizzBuzzMap.set('Fizz', 3);
fizzBuzzMap.set('Buzz', 5);
fizzBuzzMap.set('FizzBuzz', 15);
const fizzBuzz = (n) => {
let result = '';
fizzBuzzMap.forEach((value, key) => {
if (n % value === 0) {
result += key;
}
});
return result || n;
};
3:40. I can't wait to see that applied to
public defaultValue = defaultTrue;
public pointlessClassPropertyThatOnlyNeedsToBeInScopeForASingleFunction = defaultValue;
1:32 I reviewed way worse code. Like a big ass several thousands lines Java ETL that would try/catch every single NPE in its own block and do nothing about it. So instead of failing at the first NPE, it would continue until the end, return a status 0, except it did shit all.
Longest class name in Spring: "HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor"
I hope it's a utility class with only static methods XD
@@LudvikM Haha, now that would be funny :)
3:51 This one is for T-Shirt. Or a scarf.
And the brand should be named _Elsewhat_.
part 2?
3:33 this would be in the cpp standard library
The cursive is so good! I don't know what I'll use it for yet, but I'll use it.
7:53 Yeah, me too.... It happened to me during college. That was the momment when i realize I should get some sleep ;-;
The go default* vars might be for reference pointers in e.g. a default struct
I actually used to do a lot of 7:40 stuff in the competitive programming because algorithms to calculate it would be too slow
6:20 idiomatic C++ in 2030 be like
Because of this video I forced myself to write a scaleable FizzBuzzBazz program
I'm confused, do new programmers not know that switch/case statements exist?
I didn't understand literally any of these, and this was still entertaining.
I really don't know what's happening
1:40 there's a thing called "rethrow" that does exactly what you want here
4:39 Prime doesn't want to admit it was him that wrote it.
3:57 This reminded me of that video “I am a never nester”
so, there are some programming languages developed exclusively to least ammount of characters code challenges, so they have some pretty complex semantics.
oh, I thought this was going to be a tutorial on programming drone software for the US Army.
Oh that makes sense, and fits with my perspective that I'm an absolute clown... 0:57
5:02 as an interjection to the fact that print takes multiple arguments, that is fine, and any other context...
Actually, I would argue that using non-branching code would be better. [To implement fizzbuzz]
where is the moz://a video ?
why would you ever want to write fizzbuzz with a map?
Lol, I was looking at the thumb trying to understand why. Then I saw the title
It's great that after 3 years in programming I understand every single joke. My wife looks at me like I am crazy.
Soundrack from The Incredibles - Mr. Incredible learns the truth
WOW, you were able to watch a whole video without interrupting it. What a miracle :)
The only reason why I don't fuck up with .sort() still to this day despite knowing this is that I implemented an O(n) heap-sort variant in the codebase and calling that anyways :D :D :D