FizzBuzz: One Simple Interview Question

Поделиться
HTML-код
  • Опубликовано: 24 дек 2024

Комментарии • 7 тыс.

  • @jamesthompson2065
    @jamesthompson2065 4 года назад +8919

    "Repeating yourself like this is a sign of dodgy code."
    This is a personal and unwarranted attack on my way of life sir.

    • @jamesfoo8999
      @jamesfoo8999 4 года назад +328

      "Repeating yourself like this is a sign of dodgy code."
      This is a personal and unwarranted attack on my way of life sir.

    • @ejgoldlust
      @ejgoldlust 4 года назад +174

      @@jamesfoo8999 "Repeating yourself is a si

    • @nbee4981
      @nbee4981 4 года назад +43

      @@ejgoldlust @UC1OdUjZdTpo85Umes5LMVkg^^^^^^^ What they said.
      Hey, repeating what someone else did is just efficient.

    • @yeshesdevi
      @yeshesdevi 3 года назад +46

      A little DRY humor?
      (OK, I'll be quiet now.)

    • @MoMoneyMoritz
      @MoMoneyMoritz 3 года назад +21

      never before have i so been so deeply offended by something is entirely agree with XD

  • @Jams848484
    @Jams848484 3 года назад +5993

    "I'll leave fixing that as a problem for someone else"
    Yep Tom is definitely a programmer.

    • @aurelia8028
      @aurelia8028 3 года назад +181

      Or a proffessor at a university...: "The verification of this proof is left up to the reader"

    • @yuhyi0122
      @yuhyi0122 3 года назад +1

      @@aurelia8028 🤣🤣🤣👍🏻

    • @deathZor42
      @deathZor42 2 года назад +45

      Not really a JavaScript programmer at all but to save on if statements:
      for (var i = 1; i < 100;i++)
      {
      var output = "";
      var division_test = {3: "Fizz", 5: "Buzz"};
      for(var key in division_test){ if (i % key == 0) output += division_test[key]; }
      if (output == ""){ output = i; }
      console.log(output);
      }
      it's relatively trivial to fix, there is likely a more elegant solution for the whole problem, but meh it works and solves the repeating code problem.

    • @lucusekali5767
      @lucusekali5767 2 года назад +2

      @@deathZor42 nice

    • @hotwaff
      @hotwaff 2 года назад +25

      @@deathZor42 division_test should be moved out of the loop. It's a constant and doesn't need to be reset each pass.

  • @Enke796
    @Enke796 7 лет назад +5859

    6:32 "But I'll leave fixing that is a problem for someone else."
    This guy codes.

  • @78-h
    @78-h 3 года назад +2733

    "whoever comes along to maintain your code once you're done with it"
    AKA: future you in 6 months

    • @zainmushtaq4347
      @zainmushtaq4347 3 года назад +280

      "When I wrote this code, only God and I understood what it did."
      "Now... only God knows."

    • @Chicken.
      @Chicken. 3 года назад +21

      @@zainmushtaq4347 That's me after I come back to an old project.

    • @drsch
      @drsch 3 года назад +33

      That scene from LOTR comes to mind in Moria, "I have no memory of this place...."

    • @sara-n5q
      @sara-n5q 3 года назад +21

      "What moron wrote this??" -> sees it's you on git blame -> "Oh.."

    • @zenpharaohs
      @zenpharaohs 3 года назад +24

      It sound extravagant to write code that defends against a determined opponent who knows everything about your code and how best to conceal errors from you; until you realize that opponent is you six months ago....

  • @Am-Not-Jarvis
    @Am-Not-Jarvis 4 года назад +2460

    "I'll leave fixing that as a problem for someone else"
    This proof is left as an exercise for the reader

    • @0colorad0
      @0colorad0 4 года назад +40

      Using a hash/dictionary/js object/map/whatever it might be called
      ```
      (1..100).each do |number|
      options = { 3 => "Fizz", 5 => "Buzz", 7 => "Whatever" }
      output = " "
      options.each do |factor, word|
      output += word if number % factor == 0
      end
      output = number if output == " "
      puts output
      end
      ```

    • @victoriencornet5714
      @victoriencornet5714 4 года назад +15

      ​@@0colorad0 Here, I guess the answer to "I'll leave fixing that problem to someone else" is:
      function replace(double number, double divisor, String replacer){
      if (number%divisor=0) return replacer;
      return "";
      }
      function fizzbuzz(int end){
      for (i in 1 to end){
      String output=replace(i,3,"Fizz");
      output+=replace(i,5,"Buzz);
      if (output=="") output=i;
      print(output)
      }
      }

    • @ananttiwari1337
      @ananttiwari1337 4 года назад +4

      @@0colorad0 what is that programming language? Ada? C?

    • @deleteduser84
      @deleteduser84 3 года назад +1

      @@ananttiwari1337 looks like ruby

    • @integralboi2900
      @integralboi2900 3 года назад +7

      Math textbooks in a nutshell.

  • @michaelgray9112
    @michaelgray9112 7 лет назад +14204

    I'm a bit late but I'll post my Python solution:
    import fizzbuzz

    • @Trekeyus
      @Trekeyus 5 лет назад +517

      I like the way you think

    • @waynezor
      @waynezor 5 лет назад +640

      import fizzbuzz
      fizzy = fizzbuzz.Fizzbuzz()
      fizz = fizzy. fizzbuzz(start=1, stop=11)
      print(fizz)
      1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11
      easy :-)

    • @Kamel419
      @Kamel419 4 года назад +220

      lmao painfully accurate

    • @videopsybeam7220
      @videopsybeam7220 4 года назад +313

      I kept looking for that "Read More" button and never found it.

    • @razordu30
      @razordu30 4 года назад +121

      FYI - I've chuckled at this joke every so often for at least a year.

  • @5Zacc
    @5Zacc 5 лет назад +2234

    “Have a go at making fizzbuzz yourself”
    Me

    • @1414fritz
      @1414fritz 4 года назад +46

      const numbersToReplace = [ [3,'Fizz'], [5,'Buzz'] ]
      for(i=1;i !(i % replacement[0]))
      console.log( r.length ? r.map(result => result[1]).join('') : i )
      }

    • @MrOod67
      @MrOod67 4 года назад +96

      @@1414fritz you have misunderstood the problem. It's multiples of 3&5 (so 6,9 etc) not simply replacing 3 or 5

    • @existence.5806
      @existence.5806 4 года назад +81

      @@1414fritz tf is this 😵

    • @ivanomatrisciano3828
      @ivanomatrisciano3828 4 года назад +69

      @@1414fritz you need an exorcism

    • @-.---.-.-.-
      @-.---.-.-.- 4 года назад +76

      @@MrOod67 you have misunderstood his code, that is what it does, just not in a very clean way.

  • @markreynolds5384
    @markreynolds5384 2 года назад +430

    The use of “i” as the index for loops is historical. In the 1960s and 1970s Fortran was the dominate programming language. It is the precursor of most languages today. Fortran used variables that started with i,j,k,l,m and n as default integer variables. Programmers got into the habit of using these single letter variables as simple integer variables in loops so they did not have to go back and add them to their integer declarations. Over time this became so widely used that everyone started assuming that if they saw these single character variables then they were index variables in loops. That coding habit moved with the programmer as they moved to new languages.

    • @jackismname
      @jackismname 2 года назад +64

      This itself comes from mathematics, where sums over numbers is done with regards to the INDEX number, hence i.

    • @eTiMaGo
      @eTiMaGo 2 года назад +25

      @@jackismname That's how I learned it as well, and x,y,z are just brought over from mathematics. "foo" and "bar" are fascinating, though :D

    • @julianbrown1331
      @julianbrown1331 Год назад +6

      @@jackismname The origins go back to Arabic algebra (as opposed to Greek), i has nothing to do with index, at least not in the way you're thinking

    • @jackismname
      @jackismname Год назад +5

      @@julianbrown1331 Got it, I realize I made a big/ erroneous assumption here!

    • @saccerzd
      @saccerzd Год назад +4

      I always assumed - probably incorrectly - that i meant integer.

  • @dragmire3D
    @dragmire3D 4 года назад +3477

    I remember trying to make a tic-tac-toe game in the 'Introduction to Programming' class in high school.
    It ended up as something like 88 pages of if/else statements.
    I was just happy it worked...

    • @FinnishArmy
      @FinnishArmy 4 года назад +80

      dragmire3D I had to code a shift-tac-toe instead of tic-tac-toe. Try doing that with if/else statements...

    • @masoodjalal1152
      @masoodjalal1152 4 года назад +242

      We got a project to make a simple atm machine as a freshman and I made it in around 600 lines of code. It did work then, but now I don't even understand what the hell I did and how tf it worked. Later when I got some good understanding of the language(C++), I decided to do it again and this time it took about 200lines of code to do it. and most of the lines were just empty lines with braces to keep a clean readable code.

    • @ignaciosavi7739
      @ignaciosavi7739 4 года назад +29

      I wanna see that code

    • @anushakabber2709
      @anushakabber2709 4 года назад +49

      I am a freshman and I'm basically at the stage you guys are describing. I bodged my way through converting simple C code to python in around 700 lines of code and it hardly works 😓 we were asked to write it in C.

    • @nerze3157
      @nerze3157 4 года назад +67

      @@anushakabber2709 C as a freshman ? Your teacher is a sadist, or do you mean C++ ?

  • @MrTrees
    @MrTrees 5 лет назад +6917

    Interviewer: “write this code for us”
    Me, a professional software developer: *googles the code because someone out there has already done it in a better way than you ever will*

    • @fieldmarshal7298
      @fieldmarshal7298 4 года назад +634

      Work smart; not hard.

    • @yugimumoto1
      @yugimumoto1 4 года назад +286

      @@WinterSnowism very true. Don't copy paste deep learning AI code and then expect people to just not talk to you about it.

    • @jamesmurphy7193
      @jamesmurphy7193 4 года назад +54

      I recommend you avoid the field of quantum computing then

    • @Puerco-Potter
      @Puerco-Potter 4 года назад +156

      Most of the time I can write a solution as good as that, but would take me hours of fine tuning. Or I can read one solution online, say "that makes sense to me" and go on with my life. I copy the solution, not the code itself, even if I copy the code.

    • @teemuleppa3347
      @teemuleppa3347 4 года назад +6

      @@fieldmarshal7298 i dont think you understand the word "smart"...

  • @ashleygchannel
    @ashleygchannel 5 лет назад +7016

    I watched this video a day before my interview... This question came up... I got the job. Felt like I cheated 😂

    • @anneaunyme
      @anneaunyme 5 лет назад +1712

      The quickest way to code something is often to look up on the Internet if someone already did it. You managed to have already done that before you were asked the problem, so really you are more than qualified for the job.

    • @VolkanKorki
      @VolkanKorki 5 лет назад +133

      Anne Aunyme Papa Bless RUclips recommendations... (for today)

    • @JonasHamill
      @JonasHamill 5 лет назад +281

      I saw this video a couple weeks after my interview, this questions came up.. I didn't get the job. Wish I'd cheated

    • @timchanux
      @timchanux 5 лет назад +157

      In real life everybody looks up stack-overflow anyways

    • @roguishpaladin
      @roguishpaladin 5 лет назад +69

      So, has your ability for code prognostication extended into the tasks you've been asked to do? There's a huge market for people who know what to look up on Stack Overflow before they're even given a task.

  • @Minimax04
    @Minimax04 3 года назад +1076

    Tom: ‘Don’t leave things in such a mess for someone else.’
    Also Tom: I’ll leave that for someone else to fix’
    Tom absolutely nailing your everyday dev, there.

  • @MsAnonymousFangirl
    @MsAnonymousFangirl 4 года назад +1377

    So I know it's been 3 years and you'll probably never see this, but I just wanted you to know that this video inspired me to start coding again. I'm a very, very beginner programmer. I learned a tiny bit of JavaScript from Khan Academy a few years ago. I saw this video and went "HEY, WAIT! I could do that!" and then I paused the video and I went to Khan academy's program editor. Albeit using the println command because I can't use console.log there, I wrote your second actually successful program (the one with the else statements), exactly, line for line. And of course, as you said, it was still dodgy, but coming back to the video and seeing it listed as the slightly better solution than the worst one was invigorating. I wrote this! I made it work! and I didn't do it in the worst way either! Then, immediately, you gave me steps and strategies to improve, so now I'm inspired to continue. Thank you for making this video!

    • @raptora60
      @raptora60 4 года назад +33

      Just Monika.

    • @flockenlp1
      @flockenlp1 4 года назад +54

      Thats the beauty of coding, when you figure something out and it works. That's why I do it too.

    • @uzidayo
      @uzidayo 4 года назад +5

      Nice

    • @juanma9868
      @juanma9868 4 года назад +12

      So? How are you doing 3 months later?

    • @vishnusingh4118
      @vishnusingh4118 3 года назад +6

      More power to you!
      If you get stuck, please feel free to ask

  • @Dumdumshum
    @Dumdumshum 4 года назад +1788

    Bodging like that in techie environs is called spaghetti code. It can sometimes be useful to prevent your company deciding you're redundant if you're the only one who can easily figure out what you've done.

    • @DrPumpkinz
      @DrPumpkinz 4 года назад +220

      ​@Shreyash Adappanavar If you're the only person who knows what your code says, if your company wants to fire you, whoever they get to replace you will have to figure out your garbled mess.

    • @nagitokomaeda3237
      @nagitokomaeda3237 4 года назад +14

      Spaghetti code can easily be avoided by rewriting it and using comments.

    • @DrinkCoffeeRun
      @DrinkCoffeeRun 4 года назад +152

      I swear the whole "I'm the only one who can read this" doesn't ever work out. Most companies will just hire a contractor to rewrite your code, but with comments. Companies don't care about you or your code, they just want the end product to work.

    • @stevenhart6788
      @stevenhart6788 4 года назад +42

      I was working in a relatively new position at a company and their database was total crap so I built them a new on and transferred all the data over.
      I'm kind of worried about what it looks like now since it's been 3 years since I left and I think I was the only one in my office who knew how to design a database in Access.

    • @RWBHere
      @RWBHere 4 года назад +126

      @@stevenhart6788 I did something similar with a recurring seasonal job. Their detailed data on over 12,000 people was in one humongous, messy spreadsheet, which was almost impossible to search or query quickly, and full of repeats and errors, whereas my replacement database was a fraction of the size and fully relational. It looked almost identical to the old spreadsheet to users, but was far quicker, more intuitive, and above all, more reliable.
      Every time I returned, after 5 months' absence, someone in the IT Department had reverted it back to a huge, messy spreadsheet which I had to sort out before I could do my job. This went on for several years, after which I discovered that the problem was that nobody in IT really understood the advantages of databases. I expressed my incredulity in clear and succinct terms, then left them to their own devices.
      Turns out that after 6 or 7 months, their 'improved' spreadsheet had been deleting data during each save, until, finally, someone noticed that there was something wrong. They lost almost half of their data, because a mistake in their spreadsheet, which I had pointed out at the beginning, had been re-introduced. It cost them a lot of money. Only then did they decide that a database would be better than a spreadsheet.
      In fairness, they did apologise to me when I was doing an unrelated job for them, several years later.
      Sometimes you cannot teach people; they have to learn for themselves, and, all too often, they learn things the hard way.

  • @willjones8849
    @willjones8849 6 лет назад +3180

    I do
    Print: (“1,2,fizz,4,buzz,fizz,7,8,fizz...buzz)

    • @HandledToaster2
      @HandledToaster2 5 лет назад +77

      But what if you want 1000?

    • @saldor0108
      @saldor0108 5 лет назад +384

      @@HandledToaster2 must.. copy.. and paste.. HARDER!

    • @GameCyborgCh
      @GameCyborgCh 5 лет назад +93

      Interviewer: "no do it for 1 to 10 million

    • @commenturthegreat2915
      @commenturthegreat2915 5 лет назад +247

      @@GameCyborgCh THIS IS GOING TO TAKE SOME MORE COFFEEEEEE

    • @gameriffy2458
      @gameriffy2458 5 лет назад +47

      now instead of 5 and 3... make it 12 and 10 :)
      i think coffee wont be enough anymore

  • @dotanoob466
    @dotanoob466 3 года назад +643

    Code is read way more often than it’s written. And it’s often read by people other than the original writer of said code. Which is one reason why writing clean code is so important.

    • @NmaeUnavailablesigh
      @NmaeUnavailablesigh 2 года назад +47

      And it's often read by the original writer long after they've forgotten about how they wrote it

    • @azuralmusic
      @azuralmusic 2 года назад +2

      Yep, I think the person who wrote the code reads it more times than anyone else, at least in my industry.

    • @kacpero02
      @kacpero02 2 года назад

      If your code doesn't look like deranged notes of a schizophrenic cultist can you even call yourself a programmer

    • @eTiMaGo
      @eTiMaGo 2 года назад +7

      Yep, I'd rather write code spread over a few lines, with each one doing a clear function, than doing some fancy operation all in one line then trying to figure it out 3 months later :D

    • @tomsterbg8130
      @tomsterbg8130 Год назад +2

      @@azuralmusic Messy code takes your mind away in the matter of hours. You write something, you write something else, come back, AAAAH WHAT IN THE WORLD WHO WROTE THAT (me)

  • @zombieallen
    @zombieallen 3 года назад +1043

    I've been learning C++ for just under a month and decided to take this on as soon as I learned about for loops. I managed to figure it out using those nested if-else statements, and I'm absolutely thrilled that I was even able to get it to work. I see now that my code is dodgy, but that's okay! My goal was for it to work, and that was hard enough. I hope in time I learn to think ahead and code clean, but for now I will take the win :)

    • @RutgerOlthuis
      @RutgerOlthuis 3 года назад +28

      I try to avoid else as much as you can. Using break/return statements to bail out of nested places when possible.

    • @LRM12o8
      @LRM12o8 3 года назад +37

      In C++, why not use SWITCH? Way easier to understand and expand.
      IF should only be used for decisions with two possible outcomes.
      (yes, they compile to the same, but a bunch of IFs stringed together gets confusing fast)

    • @WyvernYT
      @WyvernYT 3 года назад +35

      Agreed. At a month into learning programming you're just fine playing with loops and if-then-else statements. You're doing great; don't worry about the advanced stuff.

    • @yuhyi0122
      @yuhyi0122 3 года назад +1

      Hello if else fellow, I did it too👋🏻👋🏻

    • @nikkiofthevalley
      @nikkiofthevalley 3 года назад +1

      @@LRM12o8 You also can get stuff too long for a switch statement, in which case you probably want to do it dynamically if you can

  • @howmuchbeforechamp
    @howmuchbeforechamp 4 года назад +721

    This has taught me more about code than 2 hours of tutorials

    • @berkgaffaroglu8614
      @berkgaffaroglu8614 3 года назад +3

      bruh

    • @ammyvl1
      @ammyvl1 3 года назад +2

      @@arlingtonhynes how do you propose someone learns to code, if tutorials are not allowed

    • @arlingtonhynes
      @arlingtonhynes 3 года назад +3

      @@ammyvl1 Programming tutorials are usually written by bad programmers who don’t understand the material.
      Learning something wrong is not the same as learning it right. If you can’t grasp that, go away.
      Then again, if you didn’t understand my comment, you’re a hopeless idiot.

    • @mohit_panjwani
      @mohit_panjwani 3 года назад +2

      @@arlingtonhynes snob.

    • @arlingtonhynes
      @arlingtonhynes 3 года назад

      @@mohit_panjwani Getting it right actually matters. Clown.

  • @Conycon
    @Conycon 4 года назад +3312

    I made this in the only language I know, Scratch.

    • @CookieTheSmolFox
      @CookieTheSmolFox 3 года назад +273

      True legends code only in scratch ✌️

    • @indigoziona
      @indigoziona 3 года назад +39

      I was wondering if there's a good way to do it on the Micro:bit :)

    • @KingKamal47
      @KingKamal47 3 года назад +11

      Tynker all the way

    • @Pyranders
      @Pyranders 3 года назад +18

      I learned python so that I could code my own macros.

    • @bragapedro
      @bragapedro 3 года назад +62

      Y'all using scratch? Noobs. Real legends know that logic gates are the master coding system

  • @ciknay547
    @ciknay547 3 года назад +624

    It's funny how programmers have different priorities in terms of what they see is important. You saw it more important to avoid repeating the magic number 5, however my immediate thought was to avoid adding string concatenation, as in most languages you've increased your memory overhead.

    • @Ben--Nay
      @Ben--Nay 3 года назад +51

      especially considering that you can use a logger that just wont go to the line except if told to.

    • @sploofmcsterra4786
      @sploofmcsterra4786 3 года назад +44

      Also what if the interviewer asked them to change it so it said "Pop" on multiples of both? Then you're back to that repeat.

    • @Miscio94
      @Miscio94 3 года назад +23

      @@sploofmcsterra4786 Can't you add an exception that if the print is "FizzBuzz" change it to whatever or something?

    • @milkflys
      @milkflys 3 года назад +17

      @@Miscio94 sure, but then you're running the same tests again on the output, which was the original problem with the if else statements

    • @doomse150
      @doomse150 3 года назад +36

      @@sploofmcsterra4786 I'd say that diverges far enough from the initial assigment that it can require redoing the code. Since combining words on multiples of more than one "key number" is an integral part of the game

  • @sourcererseven3858
    @sourcererseven3858 5 лет назад +956

    Remember: The poor sod coming along in a couple years to modify that code might. be. you!

    • @daveh7720
      @daveh7720 5 лет назад +82

      It's true. I've had to go back and change my code just a few months later and I sit there, scratching my head and wondering, "what was I thinking?"

    • @tsuchan
      @tsuchan 5 лет назад +48

      If you want an easy life, always work on new projects.

    • @minguine
      @minguine 5 лет назад +28

      I've had this nightmare of an experience as the poor sod fixing bugs in 10,000 lines of repetitive code. And not just one source code, but multiple 10,000-lines of repetitive sources. A simple bug fix would take days to accomplish because the variables were scattered absolutely everywhere, in multiple huge files. Ended up just refactoring everything as I went along. Eventually having to take just 5 minutes to fix a bug with the newly refactored code because the fix would require me to just change ONE thing instead of HUNDREDS.

    • @brendanpospischil3871
      @brendanpospischil3871 4 года назад +4

      Well you will probably have to modify others code, so show some courtesy and do what you expect of others.

    • @RedwoodGeorge
      @RedwoodGeorge 4 года назад +9

      There are those rare times when I come across a piece of five year old code and think "Past me was a genius!" Not all the time, mind you, but I like it when I used to be smart...

  • @TomScottGo
    @TomScottGo  7 лет назад +876

    The second in the three "Basics" videos: this one's about code, not opinions, so let's see what people think! I think I've managed to remove all the typos from my code. And if you're wondering about the blinkenlights behind me, that's the Centre for Computing History's Megaprocessor: pull down the description for a link to more details!

    • @TheWaWPRO
      @TheWaWPRO 7 лет назад +5

      Love this.

    • @anxplodinturtle7928
      @anxplodinturtle7928 7 лет назад +4

      Tom Scott this was cool! Quick question: I could have easily solved this with my single semester of Python coding that I took in college this year. Is that normal? It seems this test is a bit easy...

    • @OrigamiMarie
      @OrigamiMarie 7 лет назад +26

      Tom Scott Always assume that the person who will maintain your code after you has violent tendencies and knows where you live.

    • @OrigamiMarie
      @OrigamiMarie 7 лет назад +13

      AnXplodinTurtle Yes this test is easy. I've only seen it as a warm-up question before moving on to harder questions, usually as a quick filter when it's suspected that the interviewee can't code their way out of a paper bag. It's super useful for that!

    • @PMakerYT
      @PMakerYT 7 лет назад +11

      AnXplodinTurtle It's supposed to be easy. It's not just about "Can you solve it?" (if you cannot, why are you applying for a coding job?), but also about *how* you approach the problem. Are you writing something that works and calling it a day? Or are you planning, weighing pros and cons, preparing for future needs?

  • @sablesoul
    @sablesoul 7 лет назад +676

    I love how his programming reflects his nature as a linguist. He approached the problem from the "word" side instead of the algo side.

    • @jsonkody
      @jsonkody 6 лет назад +25

      I would do it exactly same and I am not linguist. This problem is about words not so much about algorithms.

    • @nekogod
      @nekogod 6 лет назад +11

      When I was learning programming we were taught to always start with suedo code in plain english as it made it much easier to understand what the code was supposed to be doing
      For example if I've written "When count is greater than 7 output a message box saying limit reached" and then I write "if varx

    • @michaelscofield2652
      @michaelscofield2652 6 лет назад +7

      Do you even know what ur saying or just picked something up from a lecture at school?

    • @nekogod
      @nekogod 6 лет назад +1

      @@michaelscofield2652 yes I know what I'm saying

    • @daydodog
      @daydodog 6 лет назад +18

      Yeah we were told to pseudocode but I've found it's largely a waste of time for most problems. The only time I ever really bother is with recursive algorithms

  • @danielsummers1973
    @danielsummers1973 3 года назад +1431

    From what I've heard anecdotally, the "otherwise, print the number" is the part that new programmers often leave out. The problem isn't presented in as nearly much detail as it is in the video, and the developers get so caught up in the Fizz/Buzz/FizzBuzz thing that they forget the last part. It's not only a programming question, it's an "attention to detail" question.

    • @thepalelady
      @thepalelady 3 года назад +109

      That's scarily accurate considering I did the entire problem and forgot about printing the leftover numbers

    • @xyyx1001
      @xyyx1001 3 года назад +29

      I'd blame the interviewer for not giving me clear requirements and ask if they are in charge of hiring BAs?

    • @Liquidglitch
      @Liquidglitch 3 года назад +6

      That's a very interesting anecdote. I'm the kind of person that enjoys interviewing for a job and I'm always a tiny bit excited when I come across challenges like that
      Thanks for the insight!

    • @michaeltan7625
      @michaeltan7625 3 года назад +54

      I don’t get it. It’d be obvious you did things wrong when you just see fizz and buzz on screen. The interviewer would be a real jerk if they don’t let me compile and debug (which is a huge part of programming), and then blame me for making that type of mistake

    • @Liquidglitch
      @Liquidglitch 3 года назад +7

      @@michaeltan7625 Are interviewers meant to accommodate?
      No.

  • @ChevronTango
    @ChevronTango 7 лет назад +691

    I was always taught to code as if the person who had to maintain it after you was a bloodthirsty axe-wielding murder who knew where you lived.

    • @BrightBlueJim
      @BrightBlueJim 7 лет назад +132

      Or an older you, but in my case I guess that's the same thing.

    • @acgandhi
      @acgandhi 7 лет назад +13

      ChevronTango They probably are.

    • @xFuaZe
      @xFuaZe 7 лет назад +7

      They will become so

    • @Firem1nded
      @Firem1nded 7 лет назад +9

      It's funny, they often are.

    • @infectedp9419
      @infectedp9419 7 лет назад +8

      It's "murderer".

  • @carb0nxl
    @carb0nxl 7 лет назад +1556

    Thank you for captioning your videos!
    -a Deaf subscriber

  • @ijustfelldown
    @ijustfelldown 4 года назад +488

    I'm a Civil Engineering student, have never coded anything except "Hello World" in highschool and still understood what was going on. Felt awesome.

    • @olliefischer
      @olliefischer 4 года назад +29

      tom's just that good at teaching m8 😊

    • @snickerdoooodle
      @snickerdoooodle 4 года назад +7

      I'm a computer science major. I wound up getting a job in civil engineering
      pls help

  • @ianrasmussen5380
    @ianrasmussen5380 3 года назад +783

    "If you want, pause the video now and have a go at it"
    Me: "Good idea, let's write it in C, it's been a while."
    Me 5 hours later: "Alright I finally got a C compiler installed on Windows. What was I doing again?"

    • @ianrasmussen5380
      @ianrasmussen5380 3 года назад +26

      @@inigo8740 I cannot consider an OS with a kernel created by the person who thought git had a sensible user interface.
      And really the issue was trying to get clang to work. Basic GCC I got to install with mingw super easy. Windows feels very much not a priority for the clang project

    • @JonatasAdoM
      @JonatasAdoM 3 года назад +19

      @@inigo8740 From my point of view Windows is the dark side!

    • @kg4wwn
      @kg4wwn 3 года назад +5

      @@inigo8740 I'm running Gentoo, so it was kinda important for the compiler to already be installed.

    • @geezgus
      @geezgus 3 года назад +4

      sudo apt install build-essentials :)

    • @the.parks.of.no.return
      @the.parks.of.no.return 3 года назад

      You could probably just use arduino C

  • @widjadija
    @widjadija 4 года назад +195

    This was so easy to understand even though I have almost zero coding experience. I wish I had you as a professor

    • @KingUnity22
      @KingUnity22 3 года назад +23

      Programming is just putting logic into words and symbols. So long as you can think, you can code.

    • @christopheraplin
      @christopheraplin 2 года назад +10

      @@KingUnity22 Not to mention, once you can speak the 'language' all you're doing is googling your problems.

  • @givrally
    @givrally 3 года назад +591

    Had a question like that in an interview. I asked for specifics. Does it need to be fast ? Or short and efficient ? Does it need to use as little memory as possible ? I already had a few ideas how to do it, but only after those questions had been answered did I know what the best one was. In your job and even more importantly in your job interview, you don't want to just give an answer, you want to give the best answer, and that needs knowledge of the problem.

    • @MunyuShizumi
      @MunyuShizumi 3 года назад +50

      Maintainability also becomes a thing, especially when it comes to potential future changes. Will multiple matches always append words or is FizzBuzz for 3&5 actually a special case where appending just incidentally works? Should conditions be evaluated in a specific order? Will there be negative conditions (like with leap years)? Non-modulo conditions? Etc.
      There's at least a dozen good solutions depending on what the goals are, which makes this problem a lot more profound than it initially seems.

    • @carnap355
      @carnap355 2 года назад +6

      Its mod 3*5 elseif mod 3 elseif mod5 else i

    • @reformed_attempt_1
      @reformed_attempt_1 Год назад +3

      totally wrong. If they ask you to do it you do it. I wouldn't hire you

    • @X3zbeth
      @X3zbeth Год назад

      @@reformed_attempt_1 I wouldn't work for you then

    • @tomsterbg8130
      @tomsterbg8130 Год назад +28

      @@reformed_attempt_1 good luck hiring someone nice and competent (username checks out)

  • @unit0007
    @unit0007 7 лет назад +277

    I learned to code C from an old book from the 80s, and the book said that 'i' stands for iteration. And that's the way I have been thinking about it ever since. And a quick google search told me that convention of using 'i' to mark iterations has deep roots in mathematics, reaching way back to the pre-digital age.

    • @launchsquid
      @launchsquid 6 лет назад +7

      sounds right to me, I was told it stood for integer but I believe your explanation more.

    • @Roxor128
      @Roxor128 6 лет назад +10

      I thought of it as "iteration", "index" or "increment" depending on what the loop was doing.

    • @nosouponhead
      @nosouponhead 5 лет назад

      "i" for iterator.

    • @experimentators8699
      @experimentators8699 5 лет назад +1

      I just used i because it had no meaning, because i is a temporary variable

    • @uchihasurvival
      @uchihasurvival 5 лет назад +3

      @@launchsquid n stands for integer in general. i, j and k are used for iteration. Sounds familiar? It's also used to represent vectors in math, but in C, it's arrays.

  • @moonlifeSW
    @moonlifeSW Год назад +70

    I used fizz buzz to hire my test engineers. One time I interviewed a dozen engineers only 2 passed. Some that failed had degrees from Stanford, Yale etc.

    • @MrJuzzi3
      @MrJuzzi3 Год назад +3

      Do you mean failed as programmed it the not optimal way or did not manage to even give a working solution?

    • @moonlifeSW
      @moonlifeSW Год назад +11

      @@MrJuzzi3 I mean failed to give a working solution at all.
      Interestingly one candidate from UCSD solved it in like one minute. It just demonstrates to me that programming is about problem solving and having only knowledge won't get you very far.

    • @MrJuzzi3
      @MrJuzzi3 Год назад +2

      @@moonlifeSW Wow, that is surprising, well this does give me some confidence in my own skillset!

  • @jellie4295
    @jellie4295 7 лет назад +240

    I love this video. I actually paused and got up from my lazy ass and programmed something! And after an embarassingly long period of time it worked! Yaaaay! Thank you Tom, I'd love to watch more videos like this, and my programming teacher will be glad that I didn't forget _everything_ in the holidays :)

    • @noboilfrog9431
      @noboilfrog9431 6 лет назад +2

      Yes it made my fingers twitch too.

    • @pravinrao3669
      @pravinrao3669 6 лет назад

      it took me 3 minutes.I am not even in college just in school. class IX

    • @asgeiralbretsen
      @asgeiralbretsen 6 лет назад +38

      @@pravinrao3669 You are blissfully unaware of how you are the butt of many jokes. It's easy to tell from your narcissistic and braggy comment.

    • @Die-Coughman
      @Die-Coughman 5 лет назад +1

      same dude

    • @jamestanis3274
      @jamestanis3274 5 лет назад

      @@pravinrao3669 Doesn't count without source :-)

  • @edgeeffect
    @edgeeffect 7 лет назад +730

    using "i" as a loop variable dates back to ForTran. In ForTran, variables were one letter and most were automatically real/float but a few (I don't remember how many) starting at "i" for "Integer" were automatically integers (and ideal candidates for loop indexes). ForTran was a diabolical language. I always like to use "c" for loop counters 'cus I still get a pathetic geeky thrill out of writing "C++" and it being valid code.

    • @mspenrice
      @mspenrice 6 лет назад +16

      That probably explains why my dad used to write Sinclair BASIC progs with i and j (and occasionally k or even l) as the variables for his FOR-NEXT loops... before he ended up in management his gruntwork was a string of programming gigs on industrial mainframes that used that kind of hoary old language. Always thought it was a bit odd, and that maybe he was "leaving space" to use the lower letters for other purposes or something... (hey, I was like five years old, I knew nothing)

    • @glorylyfe8314
      @glorylyfe8314 6 лет назад +67

      i stands for index.

    • @MideoKuze
      @MideoKuze 5 лет назад +38

      ^"i for index" comes from math, as do j and k. Current Fortran specs implicitly type variables starting with various initial letters, but you can disable them.
      Fortran is still in extensive use because of its performance in vector arithmetic, interestingly enough. It's not particularly hard to write in, once you get the hang of it.

    • @albertbatfinder5240
      @albertbatfinder5240 5 лет назад +12

      The implicit integer variable names in fortran were those that started with i j k l m n. Or i to n, or the “in” crowd as I used to remember them. “In” for integer if you prefer. As a default I preferred “k”, because it doesn’t look like the numeral 1 or the lower case L. K was my kounter. This habit has persisted for 40 years.

    • @dasemmiyogurt6288
      @dasemmiyogurt6288 5 лет назад

      For some reason I use k. And if I have a second for loop in a loop then I use c.

  • @railgap
    @railgap 4 года назад +219

    from TimDay on StackOverflow: "Mathematicians were using i,j,k to designate integers in algebra (subscripts, series, summations etc) long before (e.g 1836 or 1816) computers were around (this is the origin of the FORTRAN variable type defaults). The habit of using letters from the end of the alphabet (...,x,y,z) for unknown variables and from the beginning (a,b,c...) for constants is generally attributed to Rene Descartes, (see also here) so I assume i,j,k...n (in the middle of the alphabet) for integers is likely due to him too."
    There you go.

    • @davidelrizzo
      @davidelrizzo 4 года назад +3

      I just learnt something

    • @NOTNOTJON
      @NOTNOTJON 4 года назад +1

      i is for integer
      'nuff said.

    • @QqJcrsStbt
      @QqJcrsStbt 4 года назад +2

      This would help understanding how FORTRAN ended up with i to n as integer naming initials, so far great. I was not aware of of 19th C conventions. My guess is that engineering/scientific programmers of my generation brought up on 14" Winchesters, punched tape, music ruled paper and teletype terminals developed some rigid habits through the use of FORTRAN. IBM FORTRAN was '56 maybe, I cut my teeth on FORTRAN 77 on a Perkin-Elmer, K&R came out '78? My money goes on FORTAN for 'popularising' it and their fore fathers for insping/informing them.

    • @psyarts8687
      @psyarts8687 3 года назад +2

      I j k and are actually used in linear algebra to denote the values of a vector so it’s still very common

    • @mrosskne
      @mrosskne 3 года назад

      i means iterator. this isn't a mystery. it's common knowledge.

  • @torthejackal8579
    @torthejackal8579 3 года назад +29

    I'm taking an AP computer science course, and I was so proud of my self when I went and coded a working program that played fizzbuzz before you said how to.

  • @theodorechandra8450
    @theodorechandra8450 5 лет назад +2659

    "Im writing in JS, it's not the best language, but it is one of the easiest"
    Me coding in python : what?

    • @Flackon
      @Flackon 5 лет назад +314

      Python is both an easy language to start with and a good one. JS is not.

    • @jujuProductions
      @jujuProductions 5 лет назад +16

      actl with py experience its p ez to start basic js because its almost the same just with slightly different syntax

    • @Flackon
      @Flackon 5 лет назад +130

      @@jujuProductions python has radically different syntax to JS

    • @jujuProductions
      @jujuProductions 5 лет назад +4

      @@Flackon like basic basic js

    • @chrispo7610
      @chrispo7610 5 лет назад +44

      Imo js is the worst beginner language

  • @georgedongy
    @georgedongy 4 года назад +712

    Way 3:
    print ("1")
    print ("2")
    print ("Fizz")
    print ("4")
    print ("Buzz")
    print ("Fizz")
    ..and so on

    • @ZeldagigafanMatthew
      @ZeldagigafanMatthew 4 года назад +62

      Make it work on 7s instead of fives, and run it out to 500! You've got one minute to make the edits.

    • @Ezekia
      @Ezekia 4 года назад +2

      @@1ax i mean, no

    • @tomlamba6207
      @tomlamba6207 4 года назад +3

      @@1ax oof

    • @mootwo_
      @mootwo_ 4 года назад +16

      Zeldagigafan let me just pull out this random flash drive I have that coincidentally has the file for that

    • @clock4883
      @clock4883 4 года назад +26

      @@1ax This is super true, I used to be an active roblox developer using proper programming techniques, and... To say the least, HOLY CRAP ROBLOX LUA DEVELOPERS ARE SO TERRIBLE 99.99% OF THE TIME, People would get me to work on a project because they couldn't find someone else to do it, so I'd help them out just to see that another dev had been there, only just to dump thousands of lines of spaghetti and garbled bad techniques. I'd just delete all of their code and script objects and do my job after that had been revealed to me.
      So glad I don't work with roblox development anymore.
      Apologies for any grammar errors, im too lazy to fix em

  • @luka-j-ovanovic
    @luka-j-ovanovic 4 года назад +643

    After reading some comments I came to the conclusion that "i" means one of the following:
    - index
    - iteration
    - iterator
    - increment
    - integer

    • @jackk3094
      @jackk3094 4 года назад +44

      Iterator although it could be index if you are working on arrays or something

    • @DBZM1k3
      @DBZM1k3 4 года назад +9

      Iota is another meaning. In fact languages like c++ have a function called iota which will fill array with sequentially increasing values starting from a value you decide.

    • @sn0wgleb
      @sn0wgleb 3 года назад +16

      Index is the best way to think about it. There are iterators in other languages and they are a bit different.

    • @MrKogarou
      @MrKogarou 3 года назад +21

      I assume it's originally from math... xyz and ijk are common variable/dimension names. When not using xyz coordinates, ijk is the more available set of short variable names, and thus eventually became the convention.

    • @darshan5044
      @darshan5044 3 года назад +8

      Integer best suited

  • @spitalhelles3380
    @spitalhelles3380 3 года назад +547

    dodgelord me:
    "put all numbers in a list, then change every third entry to Fizz, every fifth entry to Buzz, every fiteenth entry to Fizzbuzz, output the list"

    • @Nagol93
      @Nagol93 3 года назад +133

      Id just generate a list from 1 to 100 and replace random numbers with "Fizz", "Buzz", or "Fizzbuzz" and tell them to run it until its correct :D

    • @spitalhelles3380
      @spitalhelles3380 3 года назад +8

      @@Nagol93 how does your program know when that is?

    • @Nagol93
      @Nagol93 3 года назад +185

      @@spitalhelles3380 Thats the user's job

    • @sebgamingkid
      @sebgamingkid 3 года назад +12

      that actually isn't _too_ bad of a solution

    • @eamonearl6935
      @eamonearl6935 3 года назад +11

      @@sebgamingkid i guess it’s kind of dependent on what the OS is optimized for but i feel like usually writing to arrays is a significant bit slower than integer division

  • @Ken.-
    @Ken.- 5 лет назад +961

    "We like to see how well you can program. Can you write a program that writes out FizzBuzz one hundred times?"
    "Uh, what will this job be for?"
    "Lead Programmer for Windows 10."

    • @bramkivenko9912
      @bramkivenko9912 5 лет назад +24

      Quite rare a comment makes me laugh hard!

    • @zach7482
      @zach7482 5 лет назад +92

      Go full programmer on them. Print fizzbuzz 100 times, like they said.

    • @sergey1519
      @sergey1519 5 лет назад +29

      @@zach7482 python 3
      print ("FizzBuzz
      "*100)

    • @superhavi
      @superhavi 4 года назад +37

      Print "FizzBuzz one hundred times?"

    • @drklimbal
      @drklimbal 4 года назад +4

      100.times { puts "fizzbuzz" }

  • @dongzhuhuang6972
    @dongzhuhuang6972 7 лет назад +1255

    Easy, just hard code every number & fizz buzz

    • @user-mx4ok5me5x
      @user-mx4ok5me5x 7 лет назад +84

      Dong Huang now do it for 1-1million

    • @MrLife4sin
      @MrLife4sin 7 лет назад +26

      Duh! Obviously!

    • @Mikehikegaming
      @Mikehikegaming 7 лет назад +9

      Dong Huang i hope you are joking

    • @satibel
      @satibel 7 лет назад +80

      @Exter It's easy, make a program that writes each line of code for you.

    • @Gamez4eveR
      @Gamez4eveR 7 лет назад +6

      That's a pretty girly way to do it

  • @WilliamBoothClibborn
    @WilliamBoothClibborn 7 лет назад +101

    This is useful to know for even people looking for work experience. I had to do this exact task to apply for work experience in an IT company.
    Another good demo program to learn how to write is one to calculate a factorial of a given number.

    • @koushuu
      @koushuu 7 лет назад +1

      Isn't this pretty basic? The easier way can be done by an amateur programmer (Me included). But it's the multiple quicker approaches that make me rethink about how us as IT developer should code: both nicer-looking, smarter and more ergonomic, which is harder than it looks.

    • @deathbower
      @deathbower 7 лет назад +2

      So can FizzBuzz. As Tom said, it's about getting a feel for the programmer's style more than whether they could figure out if P = NP or something else horrendously complicated.

    • @Nathanza
      @Nathanza 7 лет назад +2

      Yes, but it's not about how difficult the task is per se. It's about how you think about the problem and how you would go about doing it. Which language you would do it in and what your code will look like. Like explained in the video, there are multiple ways it can be done and each way would show something different about the interviewee, so that's why it would be a good interview task, not because of its difficulty but of what it can show about the candidate as an exhibition of their skill and not just saying they can code.

    • @placeholdername5559
      @placeholdername5559 7 лет назад +1

      Factorial can be done like this in Java
      public static int factorial(int x)
      {
      if(x==1){return 1}
      else{return x*factorial(x-1)}
      }

    • @IonutLala
      @IonutLala 7 лет назад +7

      Calculating factorial recursively is very simple but it uses up the stack very fast.

  • @puntherline
    @puntherline 2 года назад +2

    When I watched this video about 2 years ago I couldn't understand any of the code shown in the video.
    I just happened to remember it while coding in my spare time and though I'll give it a shot now. Paused the video at 1:11 and got to work in Lua. Once I finished, I kept watching and found out that my code is essentially the same as what Tom has shown at 6:05.
    And after 6:35, leaving the problem to fix for someone else, it barely took me a minute to actually fix it. I can't tell you how good it feels to finally have a comparison between my old knowledge and my current knowledge.

  • @mg5347
    @mg5347 4 года назад +93

    'pause the video and have a go at it'
    When I did my GCSEs 12 years ago my IT teacher told me it would be a waste of money to even put me in the exam

    • @PrimeGamator
      @PrimeGamator 4 года назад +16

      What a nice teacher...

    • @brooksgunn5235
      @brooksgunn5235 4 года назад +7

      Did you prove him wrong?

    • @mg5347
      @mg5347 4 года назад +14

      @@brooksgunn5235 nope, can't use a computer for anything other than word and video games...to be fair there's not much need of a smith who codes

    • @dustinandrews89019
      @dustinandrews89019 4 года назад +1

      I had a similar experience with, but I did end up as a computer programmer.

  • @Orthotropics
    @Orthotropics 4 года назад +201

    In commodore basic:
    10 a=a+1
    20 if a/15=int(a/15) print"FIZZBUZZ" : goto 10
    30 if a/5=int(a/5) print"BUZZ" : goto 10
    40 if a/3=int(a/3) print"FIZZ" : goto 10
    50 ?a : goto 10

    • @Dexxah
      @Dexxah 4 года назад +21

      ?SYNTAX ERROR IN 20

    • @ZeldagigafanMatthew
      @ZeldagigafanMatthew 4 года назад +4

      But what if you want to make it work on 7s and 11s?

    • @raw_000
      @raw_000 4 года назад +24

      I think you failed to print the plain numbers between Fizz, Buzz and FizzBuzz

    • @Gositi
      @Gositi 4 года назад +17

      @@raw_000 "?" is short for "PRINT" in Commodore Basic, I think

    • @michalhoransky1214
      @michalhoransky1214 4 года назад +2

      goto is terrible practice

  • @seanhaile8444
    @seanhaile8444 4 года назад +17

    Tom, I watch lots of these types of videos, but yours is really just top notch. You have a real knack for clearly explaining things, particularly the important and most ambiguous areas. Top notch vid and audio as well as digital presentation.

  • @jordnisse
    @jordnisse 3 года назад +1386

    Programmers use "i" instead of other letters simply for the fact that "i" corresponds to ASCII Hex 69, nice

    • @Palewhitegamer
      @Palewhitegamer 3 года назад +96

      Not... Integer?

    • @TrenteR_TR
      @TrenteR_TR 3 года назад +294

      @@Palewhitegamer Actually because in the earliest programming languages it was called an iterator. Short i

    • @Palewhitegamer
      @Palewhitegamer 3 года назад +67

      @@TrenteR_TR this makes _way_ more sense than 'hex 69'... Thank you!

    • @JuampyRabino
      @JuampyRabino 3 года назад +70

      Usually in mathematics you use i as the index in an addition

    • @thesapphiredragon8568
      @thesapphiredragon8568 3 года назад +44

      I've always thought it was short for "index"

  • @ParanormalCacti
    @ParanormalCacti 4 года назад +15

    Think I needed to come back and thank you for this video. My friend randomly sent this to me right before my interview at NASA and it happened to be the question they gave me. Got the job, with them saying I was the only one to use the most optimal solution (which I definitely wouldn't have come up with on the spot). This was right before the pandemic shut everything down and I can't even imagine where I would be without this stroke of luck. Thank you!

  • @overlordsweg8399
    @overlordsweg8399 7 лет назад +294

    the true java way would be to have a service provider bundle with a factory for creating AbstractTransliterationFunctor's and another bundle for sending the results to any one of our 15 output formats which are specifiable through a simple eclipse rcp ui with an extendable antlr grammar

    • @lionkor98
      @lionkor98 7 лет назад +96

      get well soon

    • @DreadKyller
      @DreadKyller 7 лет назад +27

      JavaScript != Java he was using JavaScript, not Java, they are very different, the only similarity being part of their name...

    • @terimarymags
      @terimarymags 7 лет назад +4

      Overlord Sweg dude you're melting my pathetic little brain

    • @overlordsweg8399
      @overlordsweg8399 7 лет назад +19

      DreadKyller I was joking about how to implement it in an oo language like java

    • @whuzzzup
      @whuzzzup 7 лет назад +25

      google FizzBuzz Enterprise.

  • @codinghub3759
    @codinghub3759 4 года назад +25

    For anyone wondering on how to easily implement extra numbers, you can make an array of objects. Each object will contain two things, the factor( ex- 3, 5) and the string that needs to be appended( ex- "Fizz", "Buzz"). Inside the for loop, create another loop, with variable j. Check if(i % array[ j ].factor == 0){ output += array[ j ].str }
    Simple as that

  • @lilellia
    @lilellia 3 года назад +283

    A Python solution that's arguably too short for clarity.
    rules = {3: 'Fizz', 5: 'Buzz'}
    for i in range(1, 101):
    output = ''.join(repl for val, repl in rules.items() if i % val == 0)
    print(output or i)

    • @oundhakar
      @oundhakar 3 года назад +72

      It took me a good 15 minutes to read and understand that.

    • @vikumwijekoon3166
      @vikumwijekoon3166 3 года назад +8

      That's a good one.

    • @Rgriffproductions
      @Rgriffproductions 3 года назад +115

      @tr3v0r Line 1: Dictionary containing the word for each multiple
      Line 2: Start of for loop
      Line 3: Uses a set comprehension to create a tuple that contains whichever part evaluated as true. For any i in the iteration it will check if i%val == 0 is true for either val = 3 or val = 5 (the two keys in the dictionary), and if so it will put the corresponding 'Fizz' or 'Buzz' in the set. From there whatever is in the set (could be either 'Fizz', 'Buzz', both, or nothing) is joined with the empty string that was initialized right before the .join
      Line 4: If the string created in line 3 is an empty string that evaluates to false so it will output the number i, otherwise it will output whatever output string was created in the previous line

    • @WDCallahan
      @WDCallahan 3 года назад +12

      @@Rgriffproductions You took the time. You are commendable, friend.

    • @kacperroszczak6127
      @kacperroszczak6127 3 года назад +1

      good one bro

  • @hendriks_kevin
    @hendriks_kevin 5 лет назад +232

    Always program so the next person can understand what you ment to do, because it could be you in 5 years (or later).

    • @sergeant5848
      @sergeant5848 5 лет назад +36

      5 years? A couple of weeks is all it takes me to forget nowadays!

    • @JNelson_
      @JNelson_ 4 года назад

      Try 40 years.

    • @julianmeier5235
      @julianmeier5235 4 года назад +23

      If you want to keep your job, you have to write code that noone else understands. This way they can t replace you cause you re the only one who can maintain the code ;)

    • @zain4019
      @zain4019 4 года назад +4

      Julian Meier :(

    • @vishakapajapaksha4784
      @vishakapajapaksha4784 4 года назад

      @@julianmeier5235 i had a co worker who does that

  • @PGReviews
    @PGReviews 7 лет назад +1523

    Or just abuse the hell out of JS:
    for(i=0;i

    • @BrianFrichette
      @BrianFrichette 7 лет назад +83

      Kreditworks 😂 I love it.

    • @Roxor128
      @Roxor128 7 лет назад +134

      Is there a JavaScript version of the Obfuscated C Contest? That looks like it would belong in it.

    • @philadams9254
      @philadams9254 7 лет назад +193

      I think that's certainly the shortest way. I think this would win in "Code Golf" but it's not easy to read.

    • @MsHojat
      @MsHojat 7 лет назад +58

      That's nice. At least for "code golf".

    • @DaRealMaus
      @DaRealMaus 7 лет назад +35

      Very nice job, only complaint would be that it starts at 0 and goes to 99 instead of start at 1 and go to 100 :)

  • @adambruzon8339
    @adambruzon8339 4 года назад +665

    Depending on who you ask, "I" could stand for iterator, integer or index...

    • @milankowww
      @milankowww 4 года назад +57

      Or iguana for that matter. But the only correct answer is integer. Learn your Fortran already

    • @alexwales8914
      @alexwales8914 4 года назад +37

      Or the square root of -1

    • @looserty819
      @looserty819 4 года назад +14

      I use x, I feel like I'm weird

    • @edbarnard6429
      @edbarnard6429 4 года назад +14

      @@looserty819 simple algebra thought process, it's not weird. you just thought, "well i need a letter to represent a number, and everyone just uses "x" for that"

    • @DarthGTB
      @DarthGTB 4 года назад +11

      I usually use a word. in this case could be "index" or "iteration" (instead of iterator) because sometimes you are going to use that variable inside the loop, so I do that for the sake of readability

  • @ahreuwu
    @ahreuwu 3 года назад +4

    I recently took a quick js course and I can proudly say that I recognize all the code in here. I haven't put any mental effort on trying to solve the problem, but I now understand exactly what's going on where and why the last code is much better than the other!

  • @possiblykale
    @possiblykale 4 года назад +32

    I remember doing this in a computer science class, and I took the time to set up the string to add everything too, made a careful plan for my method, and my final code just ended up looking like the truly bodged code.

  • @deanmoncaster
    @deanmoncaster 5 лет назад +180

    I'd just post on stack overflow and disguise it as a game of code golf and then hand in what they gave me.

    • @groszak1
      @groszak1 4 года назад +13

      then you find out it is a duplicate

  • @mattkutschera4514
    @mattkutschera4514 4 года назад +61

    @2:50 about using 'i'. A large number of times when you're running a loop, you are also using an array. The 'i' in this particular situation is short for 'index', and is often used as the array index. In other situations, 'i' could stand for 'iterator' as you will often be iterating over some generic container of data. At least, this is what I was taught regarding the use of i in loops.
    Additionally, sometimes when you're running 2-3 dimensional loops you'll see x and y (and z for 3-dimensions), which allow for visualization of containers as 3-dimensional boxes. Some programmers will default to 'x' for single dimensional loops because of this.

    • @-T.K.-
      @-T.K.- 2 года назад +7

      also could be i j k, for more of a math background programmer.

    • @tHaH4x0r
      @tHaH4x0r 2 года назад +6

      The origins lie in the Fortran language, which is mostly deprecated now but still used sometimes. It is a language really meant for being fast with math, and thus tends to use math notations, including using i j k l m n. Any variable that starts with one of those is an integer in Fortran.

    • @antonhelsgaun
      @antonhelsgaun Год назад

      Real Gs use i and j for multidimensional arrays

  • @AndyZE123
    @AndyZE123 2 года назад +3

    Probably the most consistently interesting RUclips channel there is. Thanks for your efforts.

  • @agg4000
    @agg4000 5 лет назад +555

    1:59 “that’s not instantly translatable into code”
    [laughs in Haskell pattern matching]

    • @humm535
      @humm535 5 лет назад +23

      [laughs in Go’s switch-statements]

    • @isweartofuckinggod
      @isweartofuckinggod 4 года назад +84

      [laughs in LittleBigPlanet2 selector blocks]

    • @cryotheus115
      @cryotheus115 4 года назад +8

      [laughs in Scrap Mechanic logic blocks]

    • @igornowicki29
      @igornowicki29 4 года назад +32

      [laughs in Minecraft Command Blocks]

    • @Kevin-kb
      @Kevin-kb 4 года назад +7

      [laughs in OCaml almighty pattern matching]

  • @Blabla130
    @Blabla130 7 лет назад +116

    Now I want a video of Tom playing FizzBuzzFuzzBizzBiff

  • @chrisb9319
    @chrisb9319 5 лет назад +949

    You need an "i"terator for your loop. That's why you use i.

    • @dorijancirkveni
      @dorijancirkveni 5 лет назад +44

      *mind blown*

    • @alexkantor8238
      @alexkantor8238 4 года назад +212

      it's also the "i"ndex

    • @luckymouse1988
      @luckymouse1988 4 года назад +43

      When I was a youngin', I associated the i with the practice of "i"ncrementing

    • @RandomTomatoSoup
      @RandomTomatoSoup 4 года назад +11

      nah it's from integer

    • @jlc5639
      @jlc5639 4 года назад +3

      No it was because really old machines needed to be as efficient (short) as possible. I believe it started with machines that used punch cards as storage. Proper physical memory

  • @KanpachiGaming
    @KanpachiGaming Год назад +2

    Good point about not leaving too much of a mess for those tasked to maintain your code in the future, I've been on the receiving end of such a mess and it is an absolutely hellish experience.

  • @jesusflores-padilla2983
    @jesusflores-padilla2983 4 года назад +8

    I wish University professors would actually go through problems like this. Sometimes it's the thought process that matters the most and not necessarily the solution itself. Awesome video! Wish I had discovered it closer to when it came out.

  • @Jabrils
    @Jabrils 7 лет назад +120

    Tom, that backdrop 😍

    • @Codingale
      @Codingale 6 лет назад +7

      Oh it's Jabrils! Cool!
      I'd say Tom should do a video on machine learning but that's more your style!

  • @PhilThomas
    @PhilThomas 7 лет назад +217

    Something else to think about, the "Pretty up later" style of coding does run into an issue with my old boss's idea of "what if you get hit by a bus" theory. IE there may not be a "later" that you can use to pretty up the code, and therefore you should make sure that if it must be ugly, that there are at least notes or comments explaining what is going on.

    • @toutlemonde5017
      @toutlemonde5017 7 лет назад +65

      I don't think it's just about someone else taking over your code, though... I've definitely looked back at code I wrote six months ago and had no idea what the hell I was doing.

    • @fnorgen
      @fnorgen 7 лет назад +21

      These function names made sense at the time, but what the hell does preArgCheck do? Or initSetFolow? What was I thinking?

    • @ObjectsInMotion
      @ObjectsInMotion 7 лет назад +33

      If you get hit by a bus tomorrow better to have messy code that works than pretty code thats unfinished.

    • @draxiss1577
      @draxiss1577 7 лет назад +6

      My Algorithms and ADT's professor told the class if that they got nothing else out of her class, at least make sure to provide documentation.

    • @AOEOt31os
      @AOEOt31os 7 лет назад +2

      There's always someone else to pick up the slack and finish the work though, that's a great deal easier if the code is easy to follow and continue than it is to work through a spaghetti of mess. Bigger picture and future planning vs more immediate results.

  • @gavros9636
    @gavros9636 7 месяцев назад +1

    I raise you my habit of making every single thing a function. Functions that call functions that call more functions, functions that call themselves recursively in one case.

  • @limerence8365
    @limerence8365 4 года назад +51

    I remember watching this video ages ago and being astonished anyone could actually learn how to code. But after a lot of hard learning I have finally been able to make a one sided version of this game. (I'm using a free python 2 course, not very advanced at all). It's obviously not as complicated as a two "people" playing it but I'm just happy I could do it and it's only like 12 lines.

  • @JacobAlbano
    @JacobAlbano 7 лет назад +57

    Thanks to Javascript truthiness, you can skip the last check and do
    console.log(output || i);
    If output is still an empty string, it'll go for the "truthier" value of i -- even if i would evaluate to 0 it'll still be chosen by default by virtue of coming second.

    • @SergeofBIBEK
      @SergeofBIBEK 7 лет назад +2

      Yeah, and then you can also chain it.
      console.log(output || i || "Zero");

    • @BrienMalone
      @BrienMalone 7 лет назад +2

      This needs more likes.

    • @MsHojat
      @MsHojat 7 лет назад +1

      cool

    • @robertlinke2666
      @robertlinke2666 7 лет назад

      you sir, are a genius!
      thats efficient code!

    • @dob1997
      @dob1997 7 лет назад

      is truthiness a technical term? (i hope it is)

  • @manycoreprogrammingmanycor7795
    @manycoreprogrammingmanycor7795 7 лет назад +143

    Of course, FizzBuzz assumes that people should be thinking of architecture and the updating process all the time. What I think happens is that people choose the path of least resistance.
    It's a small program that isn't expected to change that much? Quick-and-dirty usually works just fine.
    You're working on creating the next-gen operating system? Architecture is a must.
    So when they see a short list of simple product requirements (that don't even imply coding for the future), architecture isn't really going to matter. Scale the program up and they'll change priorities.
    Hence why this test isn't indicative of how good a programmer is.
    def fizzbuzz(k):
    div3 = (k%3 == 0)
    div5 = (k%5 == 0)
    if (div3 and div5):
    print "FizzBuzz"
    elif (div3):
    print "Fizz"
    elif (div5):
    print "Buzz"
    else:
    print k
    def game(list_of_numbers, func):
    for k in list_of_numbers:
    func(k)
    game(range(1,101), fizzbuzz)
    There, a simple python program that takes a univariate function and a list of numbers to play a game. At no point do I expect any changes. If there's a major change, no amount of abstraction would help ("oh, you want a banking system now?"). If there's a single minor change, it wouldn't take that long to modify the program. The only time you'd consider changing the algorithm is when the update process simply doesn't scale anymore.
    For example, insert sort is still fine for

    • @huntforerror
      @huntforerror 6 лет назад +7

      i personally would do it this way:
      def FizzerBuzzer(rng,*numargs,**wordargs):
      for x in range(1,rng+1):
      s = ""
      for i,word in zip(numargs,wordargs.values()):
      if x % i == 0:
      s += word
      print(x if s == "" else s)

    • @hermanappelgren
      @hermanappelgren 6 лет назад +15

      That's why I believe the follow-up questions are crucial. For two and maybe three values the if approach is feasible, but already at four values you have 16 distinct cases to handle. If you then don't come up with a different solution, that to me is a red flag.

    • @Deliverygirl
      @Deliverygirl 5 лет назад +27

      This is exactly how it should be, scope of a project is extremely important when deciding what the implementation would be. Nobody wants you to spend a week writing a single line, ultra efficient program if it will only be used sporadically and with a minor task. Resource allocation (programmer time, execution time) is almost as important as the actual programming itself.

    • @dm9910
      @dm9910 5 лет назад +12

      The whole point of the test is to check that the programmer knows what it means to write maintainable code and can break down a problem and simplify it. Anyone who can write maintainable and readable code can churn out a quick and dirty hack if needed, but that's not true in reverse.
      I would hope that your average person interviewing to be a professional software developer would be on the ball enough to realize that the interviewer is not really asking "can you do an extremely basic programming task that any amateur could do?" but rather "can you demonstrate that writing good code comes naturally to you?".

    • @listlessh
      @listlessh 5 лет назад +1

      I think asking questions about the nature of the project would also be appropriate. As a freelancer, this is something I need to do often to avoid wasting my own time. On the other end (as client/agent), I've had a few people go really overboard on a simple project which I then had to simplify myself.

  • @MonsPubis7
    @MonsPubis7 3 года назад +66

    4 years of programming in college, and youve explained it better than 90% of tutorials and all my college professors combined. Thats actually hilarious, maybe you should make a separate channel dedicated to teaching people, obviously you are, youre teaching solutions, problems, and everything really with the world. Id sub to that channel in a heartbeat(yes ik how to code, but seeing another perspective and showing it and explaining it better is always a priority to me) i never like youtube videos, but im givin this vid a like

    • @jd-zr3vk
      @jd-zr3vk 2 года назад +3

      You are hearing this again and it is just now clicking. You understand because of our college professors.

    • @KidsLearnHTML
      @KidsLearnHTML Год назад +2

      I know you're telling the truth. I feel sad and angry about this! This is from an online article about James Altucher (chess master and best selling author) . It said: Altucher says he ended up taking on "massive" debt to go to Cornell, where he majored in computer science. He then attended graduate school, though he dropped out before finishing the degree. He says he still didn't have the skills needed to enter the workforce.
      *"When I finally got a job, I was so bad at computer programming they had to send me to remedial classes for two months so I could be good enough to do the minimum required at my job," he explains. "So I'm not sure what I went to college for."*

    • @PanosPitsi
      @PanosPitsi Год назад +2

      He taught you how to make a hello
      World loop your professors taught you more important stuff I’d hope

  • @mr.hi_vevo414
    @mr.hi_vevo414 4 года назад +4

    Decided to try it out in Excel and finished it in about 5 minutes
    =IFS(AND(A1/3=INT(A1/3),A1/5=INT(A1/5)),"FizzBuzz",A1/3=INT(A1/3),"Fizz",A1/5=INT(A1/5),"Buzz",TRUE,A1)
    This is with 1-100 down in column A

  • @ndxdirectorscut
    @ndxdirectorscut 4 года назад +73

    i like to call my Programming style "versatile Bodge"
    basically i bodge things together, however I use alot of variables to let me edit the code later without editing the logic. i like to believe it makes it easy to edit for non-programmers as i have all the variables properly named at the top

    • @lucky-segfault
      @lucky-segfault 3 года назад +1

      Honestly id rather work on code like this than just about any other, assuming you put some comments in to explain the weird or difficult to understand bits of logic

    • @StilvurBee
      @StilvurBee 3 года назад

      amen

    • @MazeFrame
      @MazeFrame 3 года назад +1

      That is how I do it for uControllers, Arduino or when doing a quick proof of concept in Processing.

  • @bestcreations4703
    @bestcreations4703 Год назад +5

    When I was making a slideshow for a programming workshop I had to present I included fizz buzz on it, and I wanted to write it in a way that was both the most simplistic and yet readable that you could since I was fitting it on a slideshow. I ended up using a string to hold my output, do the check for the fizz and buzz and if it were true I would simply append the text. Then I check if the string was empty, if so I added the number to it. Then I added a new line character and printed it. Very simple, no complicated if-else if-else or anything of the sort. Computationally it’s not doing anything super laborious either. Obviously it is not the best in any way, but it wasn’t designed to be it was designed to be compact yet digestible to starting programmers while still showing the unique ways you can solve a problem and I think I did that.

  • @snjert8406
    @snjert8406 3 года назад

    I am now fricken pondering on this for more than half an hour and I'm mad at you for bringing this into my head

  • @amirgamil
    @amirgamil 5 лет назад +117

    I like the idea of this programming problem in an interview and look forward to the day that I get asked to do it. Or be given the opportunity to ask someone to do it :)
    Only thing is... the more it gets talked about, the less effective of a question it is.

    • @SendarSlayer
      @SendarSlayer 5 лет назад +13

      So ask a similar vein of question with enough change that their ability to write this code isn't called into question.
      Or throw a curve ball after asking this one. Something so out there it shouldn't really be in this sort of program and is there to see if they can create robust code from unfavourable situations

    • @ookazi1000
      @ookazi1000 4 года назад

      One idea for a curve ball is to request code that for a given output of a fizzbuzzesque game gives the simpleist rule set that would produce that output, and if the output isn't possible, given the simple factor rules, throw an error or give some indication that the output can't be a correct output for simple fizzbuzz variation.
      I don't relative hardnesswise how this question would compare; but at a glance, I'd think it'd about the same or maybe a bit more difficult.

    • @skyblazeeterno
      @skyblazeeterno 4 года назад +1

      If you are at an interview stage the hirer should have already checked your technical competence. They are seeing HOW you solve problems not that you can do it.
      They do this in a lot of jobs not just IT. Plus you can technically get hired even if you "fail"

    • @particleman5893
      @particleman5893 4 года назад +1

      A big part of being a programmer is searching for the solution on stack overflow, so this question should be kept.

    • @Ray.Norrish
      @Ray.Norrish 4 года назад

      It's just an example of an approach

  • @thomashanson6603
    @thomashanson6603 2 года назад +3

    Thanks for making this, I haven't done any coding in a few months since my last class, it was nice to brush off the dust on it.

  • @config2000
    @config2000 4 года назад +85

    Console.log("Virus detected. Switch off immediately!");
    Phew .. Dodged a bullet there.

  • @gaoindustries8013
    @gaoindustries8013 3 года назад

    Since I code in C++, I would have just done "cout

  • @XamiNaxamis
    @XamiNaxamis 3 года назад +3

    Tried this in C++, went with a modular but super front-loaded solution by declaring two arrays with the divisible numbers to use and the strings to look for, then used pointer arithmetic to auto-calculate the length of the arrays in a nested loop that runs thru both arrays to check the counter of the bigger loop. Sightly unwieldy and I probably didn't explain it well, but it worked okay!

  • @farkler4785
    @farkler4785 3 года назад +13

    to fix the repetition part you could make the if statements a function, something like
    function isMultiple(number, multiple, result) {
    if (number % multiple == 0) { return result }
    else {return " "}
    }
    And then in the loop do:
    output += isMultiple(i, 3, "Fizz")
    output += isMultiple(i, 5, "Buzz")

    • @Misteribel
      @Misteribel 2 года назад +3

      But now you’re still repeating yourself. Instead, consider putting the ‘3’, ‘5’ etc rules in a little list, with their expected outcome, and you get a generic solution, without repetition. Make those rules an argument to the function, and it becomes composable.

  • @bengineer8
    @bengineer8 7 лет назад +29

    Ti-84 BASIC:
    :For(n,1,100
    :" "
    :If not(remainder(n,3
    :Ans+"FIZZ
    :If not(remainder(n,5
    :Ans+"BUZZ
    :If not(1-length(Ans
    :n
    :Disp Ans
    :End

    • @piteoswaldo
      @piteoswaldo 7 лет назад +1

      MATLAB:
      i=1:100;
      fizz = mod(i,3)==0;
      buzz = mod(i,5)==0;
      output = num2cell(i);
      output(fizz) = {'FIZZ'};
      output(buzz) = {'BUZZ'};
      output(fizz & buzz) = {'FIZZBUZZ'};
      disp(output')

    • @MsHojat
      @MsHojat 7 лет назад +3

      It's called TI BASIC I think. I could be mistaken, but I think all the [TI] calculators use the same language.

    • @bengineer8
      @bengineer8 7 лет назад

      They have some slight differences. Variables were once able to lowercase. (the "n" I used was the slanted one and doesn't count)

  • @maddy3852
    @maddy3852 Год назад +1

    I used to watch these when I was younger and I didn't understand them at all because I knew nothing about coding. Now I am taking a programming class and these vids are starting to make a lot more sense.

  • @self.medicate
    @self.medicate 3 года назад +52

    02:50 I always thought the "i" stood for "iterator", referring to the current object in the loop.
    Edit: Added timestamp.

    • @h4ro457
      @h4ro457 3 года назад

      But that's exactly it

    • @Siddharth9092
      @Siddharth9092 3 года назад +8

      I think "i" means "index" because looping like this comes from old languages when iterators were not there. Although I'm not sure.

    • @johnfbw79
      @johnfbw79 3 года назад

      I thought integer because they are almost always

    • @munjee2
      @munjee2 3 года назад

      And here I thought it was "increment", all of us came up with completely different answers

    • @user-xw4mu6nz4t
      @user-xw4mu6nz4t 3 года назад

      @@munjee2 It's index, increment doesn't even make sense

  • @mikes128
    @mikes128 7 лет назад +112

    A few people are speculating that _i_ is short for "iterator", or "integer". I decided to look this up and apparently it dates back to Fortran. Variables I through N defaulted to integers, where other names defaulted to floats (due to the mathematical convention of using those letters as indices) so it made sense to use i, j, k etc as loop variables. So it might mean something like "index," although the real reason is probably just that it's short and programmers are lazy.

    • @jubjub727
      @jubjub727 7 лет назад +7

      That's not correct, i was in use before Fortran. It's just an arbitrary name with no reasoning behind it or special meaning or story.

    • @livingfray2340
      @livingfray2340 7 лет назад +19

      Mathematics has used i for summations (and j and k for nested summations) for much longer though

    • @justarandompally
      @justarandompally 7 лет назад

      Sure and writers had been using i for writing for much longer... We're talking about why it's used in loops n such in code, not why it's used at all...

    • @jubjub727
      @jubjub727 7 лет назад +2

      Yes so am I. i was used in loops BEFORE Fortran.

    • @mikes128
      @mikes128 7 лет назад +3

      I mentioned the mathematical convention too. I'm aware that Fortran was basing its rule on conventions that already existed. However Fortran seems to be the language which made i-n especially useful for loops since they were implicitly treated as integers, which might be how that became a habit.
      Of course I just Googled it in about thirty seconds, so there's probably even more history I'm missing.

  • @dunebasher1971
    @dunebasher1971 7 лет назад +24

    That Megaprocessor is the most sci-fi-looking thing EVER.
    It ought to be making noises thought. Beeps, ticks, whirrs. Like a proper 60s or 70s fictional TV computer.

    • @jacobhuckins494
      @jacobhuckins494 7 лет назад +2

      would be cool to stick a little clicker on each of the LEDs and let it run

    • @bbdawise
      @bbdawise 7 лет назад +1

      I'm also imagining it running a bicycle wheel somewhere with a card in the spokes.

    • @mspenrice
      @mspenrice 6 лет назад

      attach a piezo buzzer and a couple of 555s plus the appropriate discrete components (one set for a short duration one-shot pulse, the other tuned to oscillate at a certain frequency different from all the other nearby ones) to each one? Beepboop city.

  • @twokegs1
    @twokegs1 3 года назад

    Genuinely happy to see your uploads 😁

  • @bazahaza
    @bazahaza 7 лет назад +150

    1:05 That's Numberwang !!

    • @mspenrice
      @mspenrice 6 лет назад +1

      4

    • @lravenl
      @lravenl 5 лет назад +2

      Hahaha nice to find a mitchell and webb fan in a random place

    • @roguishpaladin
      @roguishpaladin 5 лет назад +2

      @@lravenl Honestly, I suspect the shared audience between Mitchell and Webb and Tom Scott is fairly high.

    • @lravenl
      @lravenl 5 лет назад +1

      @@roguishpaladin Haha you might be right. And I am one of them.

    • @clockworkkirlia7475
      @clockworkkirlia7475 5 лет назад

      @@mspenrice *Drei-und-Zwanzig
      Das ist Nümberwang!

  • @huntmich
    @huntmich 4 года назад +72

    I feel like Tom Scott is somewhere between 25 and 50.

    • @ivan-1876
      @ivan-1876 3 года назад +6

      if "Tom Scott" > 25 and "Tom Scott" < 50:
      print("True. Tom Scott is {} age".format("unknown"))

    • @TypicallyThomas
      @TypicallyThomas 3 года назад +2

      @@ivan-1876 Yes, except... Why are your variables strings?

    • @ivan-1876
      @ivan-1876 3 года назад +1

      @@TypicallyThomas I'm not creating a Tom Scott variable because then I would need to add a _ in place of the spaces and it would look bad haha that's the whole reason

    • @wateryagarvideos5186
      @wateryagarvideos5186 3 года назад

      @@ivan-1876 Python I see?

    • @ivan-1876
      @ivan-1876 3 года назад

      @@wateryagarvideos5186 It's the only language I've learnt if you don't count scratch

  • @sofiaknyazeva
    @sofiaknyazeva Год назад +13

    Few notes and if you do it in C
    1. You can break after matching last modulo which will remove the overhead of having another if statement at the end
    2. For more efficiency, you can remove modulo checking since it's a O(n) algorithm, a larger value would significantly decrease the performance on low end systems. Computers are slower at division, especially floating point.
    3. JS console.log(...) always adds a newline at the end. If you use nodejs you can use process.stdout.write(...) which directly calls write(...) syscall without overheading of having a newline. Of course, it still buffer.
    4. C doesn't have this, so FizzBuzz will he printed on that same line.
    :)

    • @antonhelsgaun
      @antonhelsgaun Год назад +2

      What would you do instead of modulo?

    • @InstaFall
      @InstaFall Год назад

      Yea FizzBuzz would be printed but also all the other numbers that comes after a "Fizz" because you didn't add a "
      " so not a correct solution

  • @sgbirch
    @sgbirch 3 года назад +6

    Oh God, I really am old. I was already a professional programmer in the eighties when i became the a popular choice for int. FORTRAN used the variables I to N as integers. I was used most often, a habit that persists to this day.

  • @icyclimber4215
    @icyclimber4215 7 лет назад +575

    yup, this is some basic basics right here

    • @Djfragas
      @Djfragas 7 лет назад +3

      Yup, 3if commands and you are done.

    • @AaronTheGerman
      @AaronTheGerman 7 лет назад +28

      Would have been funny, if he wrote it in basic

    • @melamoli5244
      @melamoli5244 7 лет назад +17

      lithium 1817 it was easy enough for me and my low skillevel to understand what he's saying
      great video!

    • @hazersubscriber4211
      @hazersubscriber4211 7 лет назад +2

      lithium 1817 yr 9 me would find this easy, tho I'm on python not java

    • @justwitti
      @justwitti 7 лет назад +11

      Hazersubscriber obligatory this is JS not Java

  • @Tefans97
    @Tefans97 4 года назад +10

    just did this in R instead of going to sleep, feels like a good use of my time

  • @krubbles101
    @krubbles101 5 лет назад +113

    The reason that we use "i" "j" and "k" is because I- N defaulted to an integer in Fortran.

    • @clickrick
      @clickrick 5 лет назад +4

      I'm glad someone else remembers that!

    • @IngeniousIgneous
      @IngeniousIgneous 5 лет назад +17

      ijk are also hella common mathematic iterators

    • @MrCmon113
      @MrCmon113 4 года назад +2

      No, those are much older than that.

    • @TealJosh
      @TealJosh 4 года назад +2

      @@IngeniousIgneous literally almost as common in maths as xyz. Also related, lul.

    • @digitig
      @digitig 4 года назад +5

      But that just moves the problem on a step: why was I to N chosen as the default integer range?

  • @akni3547
    @akni3547 3 года назад

    I knew nothing about coding prior to this video. And that was so satisfying, him making the code more compact, bit by bit.

  • @madmanwithaplan1826
    @madmanwithaplan1826 Год назад +4

    no matter your level of coding we all agree the biggest sin in this code is no one left any notes.

  • @antontimeboy6094
    @antontimeboy6094 7 лет назад +122

    I think you made a (small) mistake when explaining for-loops. You explained it like the condition is checked after each execution of the block, but it's actually BEFORE.
    Makes some difference.
    Other than that, great video!

    • @jamesmnguyen
      @jamesmnguyen 7 лет назад +9

      In other words here's the breakdown:
      int i=0;
      while(i

    • @CasualCoreK
      @CasualCoreK 7 лет назад +27

      Frustratingly, this can depend on the programming language.

    • @turun_ambartanen
      @turun_ambartanen 7 лет назад +1

      +James Nguyen
      not if you use continue!!!
      +CasualCoreK
      Interesting. do you know any examples?

    • @hellterminator
      @hellterminator 7 лет назад +4

      +CasualCoreK He specified he's using JavaScript. The condition is definitely checked at the beginning of each cycle in JavaScript.

    • @lawrivanbuel7047
      @lawrivanbuel7047 7 лет назад +1

      Actually this is highly dependant on what language you use. in most ANSI C compilers you are correct. in Java its dependant on you JVM (for example on some JAVACard implementations this check is indeed the last call of a loop, in the form of a JMPNZ [Jump if not zero] instruction).
      Javacript its dependant on your ECMAScript implementaion so basically you do not know.
      But in Embedded C (or in optimised C) you simply do not know where the instruction is in the loop. All you know is that its called before the next iteration starts.

  • @TypicallyThomas
    @TypicallyThomas 3 года назад +35

    I made a solution in Python. I'm quite proud of it:
    rules = [[3, "Fizz"], [5, "Buzz"]]
    for i in range(1, 101):
    output = ""
    for rule in rules:
    if i % rule[0] == 0:
    output += rule[1]
    if output == "":
    output = i
    print(output)

    • @JonMW
      @JonMW 3 года назад +12

      Son, that should be a dict.
      rules = {3: "Fizz", 5: "Buzz"}
      for i in range(1, 101):
      output = ""
      for divisor, word in rules.items():
      if i % divisor == 0:
      output += word
      if output == "":
      output = i
      print(output)

    • @TypicallyThomas
      @TypicallyThomas 3 года назад +1

      @@JonMW That's also an option

    • @sohummohare6364
      @sohummohare6364 3 года назад

      Very cool

    • @yeetdeets
      @yeetdeets 3 года назад +1

      ​@@JonMW The results should be pre-calculated and put into a dict as well. Takes less time to multiply the special cases than to check every number against a logic statement with division in it.
      -----------------
      low, high = (1, 101)
      # if you don't understand the following two lines, look up "list comprehension"
      fizz = {i*3: "Fizz" for i in range(low//3, high//3)}
      buzz = {i*5: "Buzz" for i in range(low//5, high//5)}
      for i in range(low, high):
      # dict.get defaults to returning None if key doesn't exist
      # None checks as False in an if-statement
      if fizz.get(i) or buzz.get(i):
      # The default return value from dict.get can be changed with a second argument
      print(fizz.get(i, "")+buzz.get(i, ""))
      else: print(i)
      ----------------
      Trying to add the idea of a rules dict makes it into list/dict comprehension city!
      -----------------
      low, high = (1, 101)
      rules = {3: "Fizz", 5: "Buzz", 7: "Duzz"}
      results = {rk: {i*rk: rv for i in range(low//rk, high//rk)} for rk, rv in rules.items()}
      for i in range(low, high):
      # if the key doesn't exist, no list index is created. Meaning the list length will equal the number of keys found.
      resultList = [results.get(r).get(i) for r in rules if results.get(r).get(i)]
      # an empty list checks as False
      if resultList:
      # join is a string method which joins all strings in an iterable with the target string
      print("".join(resultList))
      else: print(i)
      ----------------
      This code can then be wrapped in a while loop where low and high is increased by 100 to make the game work infinitely.

    • @RideByAquib
      @RideByAquib 3 года назад

      mine is quite traditional :
      for i in range(1, 101):
      if (i % 3 == 0) & (i % 5 == 0): print(i, ": FizzBuzz")
      elif i % 3 == 0: print(i, ": Fizz")
      elif i % 5 == 0: print(i, ": Buzz")
      else: print(i)

  • @glenmonks4489
    @glenmonks4489 Год назад

    I think I commented to this effect five years ago, but I want to do so again: This interview question has saved my company thousands of points and tens of thousands of hours. Before we did this test, we employed two programmers who quite simply couldn't program anything beyond what I'd call "scripts" that executed lineally from top to bottom with no internal logic.
    What's more, the "feel" we get from a programmer as they do this test has turned out to reflect their real-life practices for years to come. The diligent perfectionists and the "just get it done" types show up, and our company benefited from having a balance of each of those types. We have a programmer who totally aced this test, and he continued to be the star programmer for many years.