fizzbuzz

5 results back to index


pages: 722 words: 90,903

Practical Vim: Edit Text at the Speed of Thought by Drew Neil

Bram Moolenaar, don't repeat yourself, en.wikipedia.org, fault tolerance, finite state, fizzbuzz, off-by-one error, place-making, QWERTY keyboard, web application

So if we were editing a file called ~/quickfix/fizzbuzz.js, then running :make inside Vim would be equivalent to running this in the shell: => ​​$ export NODE_DISABLE_COLORS=1​​ => ​​$ nodelint ~/quickfix/fizzbuzz.js​​ <= ​​~/quickfix/fizzbuzz.js, line 2, character 22: Unexpected '++'.​​ ​​for (i=1; i <= 100; i++) {​​ ​​~/quickfix/fizzbuzz.js, line 3, character 15: Expected '===' ...​​ ​​if(i % 15 == 0) {​​ ​​~/quickfix/fizzbuzz.js, line 5, character 21: Expected '===' ...​​ ​​} else if(i % 5 == 0) {​​ ​​~/quickfix/fizzbuzz.js, line 7, character 21: Expected '===' ...​​ ​​} else if(i % 3 == 0) {​​ ​​~/quickfix/fizzbuzz.js, line 12, character 2: Unexpected ';'.​​ ​​};​​ ​​5 errors​​ By default, nodelint highlights errors in red using ANSI color codes.

First, we’ll configure Vim so that running :make calls nodelint,[30] a command-line interface to JSLint.[31] It depends on Node.js and can be installed using NPM simply by running this:[32] => ​​$ npm install nodelint -g​​ As a test case, we’ll use this JavaScript implementation of FizzBuzz: quickfix/fizzbuzz.js ​​var i;​​ ​​for (i=1; i <= 100; i++) {​​ ​​ if(i % 15 == 0) {​​ ​​ console.log('Fizzbuzz');​​ ​​ } else if(i % 5 == 0) {​​ ​​ console.log('Buzz');​​ ​​ } else if(i % 3 == 0) {​​ ​​ console.log('Fizz');​​ ​​ } else {​​ ​​ console.log(i);​​ ​​ }​​ ​​};​​ Configure ‘:make’ to Invoke Nodelint The ‘makeprg’ setting allows us to specify the program that will be called when we run :make (see 'makeprg' ​).

if(i % 15 == 0) {​​ ​​~/quickfix/fizzbuzz.js, line 5, character 21: Expected '===' ...​​ ​​} else if(i % 5 == 0) {​​ ​​~/quickfix/fizzbuzz.js, line 7, character 21: Expected '===' ...​​ ​​} else if(i % 3 == 0) {​​ ​​~/quickfix/fizzbuzz.js, line 12, character 2: Unexpected ';'.​​ ​​};​​ ​​5 errors​​ By default, nodelint highlights errors in red using ANSI color codes. Setting NODE_DISABLE_COLORS=1 mutes the colors, which makes it easier to parse the error messages. Next, we have to make Vim parse the output from nodelint so that it can build a quickfix list from the results. We can approach this problem in two ways: we could configure nodelint so that its output resembled the error messages generated by make, which Vim already understands, or we could teach Vim how to parse the default output from nodelint.


Practical Vim, Second Edition (for Stefano Alcazi) by Drew Neil

Bram Moolenaar, don't repeat yourself, en.wikipedia.org, fault tolerance, finite state, fizzbuzz, off-by-one error, place-making, QWERTY keyboard, web application

So if we were editing a file called ~/quickfix/fizzbuzz.js, then running :make inside Vim would be equivalent to running this in the shell: ​=> ​$ export NODE_DISABLE_COLORS=1​ ​=> ​$ nodelint ~/quickfix/fizzbuzz.js​ ​<= ~/quickfix/fizzbuzz.js, line 2, character 22: Unexpected '++'. ​ for (i=1; i <= 100; i++) { ​ ~/quickfix/fizzbuzz.js, line 3, character 15: Expected '===' ... ​ if(i % 15 == 0) { ​ ~/quickfix/fizzbuzz.js, line 5, character 21: Expected '===' ... ​ } else if(i % 5 == 0) { ​ ~/quickfix/fizzbuzz.js, line 7, character 21: Expected '===' ... ​ } else if(i % 3 == 0) { ​ ~/quickfix/fizzbuzz.js, line 12, character 2: Unexpected ';'. ​ }; ​ 5 errors By default, nodelint highlights errors in red using ANSI color codes.

First, we’ll configure Vim so that running :make calls nodelint,[26] a command-line interface to JSLint.[27] It depends on Node.js and can be installed using NPM simply by running this:[28] ​=> ​$ npm install nodelint -g​ As a test case, we’ll use this JavaScript implementation of FizzBuzz: quickfix/fizzbuzz.js ​ ​var​ i; ​ ​for​ (i=1; i <= 100; i++) { ​ ​if​(i % 15 == 0) { ​ console.log(​'Fizzbuzz'​); ​ } ​else​ ​if​(i % 5 == 0) { ​ console.log(​'Buzz'​); ​ } ​else​ ​if​(i % 3 == 0) { ​ console.log(​'Fizz'​); ​ } ​else​ { ​ console.log(i); ​ } ​ }; Configure ‘:make’ to Invoke Nodelint The ‘makeprg’ setting allows us to specify the program that will be called when we run :make (see 'makeprg'ⓘ).


Practical Vim by Drew Neil

Bram Moolenaar, don't repeat yourself, en.wikipedia.org, fault tolerance, finite state, fizzbuzz, off-by-one error, place-making, QWERTY keyboard, web application

So if we were editing a file called ~/quickfix/fizzbuzz.js, then running :make inside Vim would be equivalent to running this in the shell: ​=> ​$ export NODE_DISABLE_COLORS=1​ ​=> ​$ nodelint ~/quickfix/fizzbuzz.js​ ​<= ~/quickfix/fizzbuzz.js, line 2, character 22: Unexpected '++'. ​ for (i=1; i <= 100; i++) { ​ ~/quickfix/fizzbuzz.js, line 3, character 15: Expected '===' ... ​ if(i % 15 == 0) { ​ ~/quickfix/fizzbuzz.js, line 5, character 21: Expected '===' ... ​ } else if(i % 5 == 0) { ​ ~/quickfix/fizzbuzz.js, line 7, character 21: Expected '===' ... ​ } else if(i % 3 == 0) { ​ ~/quickfix/fizzbuzz.js, line 12, character 2: Unexpected ';'. ​ }; ​ 5 errors By default, nodelint highlights errors in red using ANSI color codes.

First, we’ll configure Vim so that running :make calls nodelint,[26] a command-line interface to JSLint.[27] It depends on Node.js and can be installed using NPM simply by running this:[28] ​=> ​$ npm install nodelint -g​ As a test case, we’ll use this JavaScript implementation of FizzBuzz: quickfix/fizzbuzz.js ​ ​var​ i; ​ ​for​ (i=1; i <= 100; i++) { ​ ​if​(i % 15 == 0) { ​ console.log(​'Fizzbuzz'​); ​ } ​else​ ​if​(i % 5 == 0) { ​ console.log(​'Buzz'​); ​ } ​else​ ​if​(i % 3 == 0) { ​ console.log(​'Fizz'​); ​ } ​else​ { ​ console.log(i); ​ } ​ }; Configure ‘:make’ to Invoke Nodelint The ‘makeprg’ setting allows us to specify the program that will be called when we run :make (see 'makeprg'ⓘ).


pages: 270 words: 64,235

Effective Programming: More Than Writing Code by Jeff Atwood

AltaVista, Amazon Web Services, barriers to entry, cloud computing, endowment effect, fail fast, Firefox, fizzbuzz, Ford Model T, future of work, game design, gamification, Google Chrome, gravity well, Hacker News, job satisfaction, Khan Academy, Kickstarter, loss aversion, Marc Andreessen, Mark Zuckerberg, Merlin Mann, Minecraft, Paul Buchheit, Paul Graham, price anchoring, race to the bottom, recommendation engine, science of happiness, Skype, social software, Steve Jobs, systems thinking, TED Talk, Tragedy of the Commons, web application, Y Combinator, zero-sum game

So I set out to develop questions that can identify this kind of developer and came up with a class of questions I call “FizzBuzz Questions,” named after a game children often play (or are made to play) in schools in the UK. An example of a Fizz-Buzz question is the following: Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz.” Most good programmers should be able to write out on paper a program which does this in a under a couple of minutes.

I assumed anyone applying for a job as a programmer had already crossed this chasm. Apparently this is not a reasonable assumption to make. Apparently, FizzBuzz-style screening is required to keep interviewers from wasting their time interviewing programmers who can’t program. Lest you think the FizzBuzz test is too easy — and it is blindingly, intentionally easy — a commenter to Imran’s post notes its efficacy: I’d hate interviewers to dismiss [the FizzBuzz] test as being too easy – in my experience it is genuinely astonishing how many candidates are incapable of the simplest programming tasks. Maybe it’s foolish to begin interviewing a programmer without looking at their code first.

Good candidates for the coding problem are verifiably simple, with basic loops or recursion and perhaps a little formatted output or file I/O. All we want to know is whether they really do know how to program or not. Steve’s article predates it, but I’d be remiss if I didn’t mention Why Can’t Programmers.. Program? here. The FizzBuzz problem is quite similar, and it’s shocking how often interviewees can’t do it. It’s a bit hard to comprehend, like a potential truck driver somehow not being able to find the gas pedal or shift gears. Object-Oriented Programming Design a deck of cards that can be used for different card game applications.


pages: 1,076 words: 67,364

Haskell Programming: From First Principles by Christopher Allen, Julie Moronuki

book value, c2.com, en.wikipedia.org, fail fast, fizzbuzz, functional programming, heat death of the universe, higher-order functions, natural language processing, spaced repetition, tiling window manager, Turing complete, Turing machine, type inference, web application, Y Combinator

But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. A typical fizzbuzz solution in Haskell looks something like: fizzBuzz :: Integer -> String fizzBuzz n | n `mod` 15 == 0 = | n `mod` 5 == 0 = | n `mod` 3 == 0 = | otherwise = "FizzBuzz" "Fizz" "Buzz" show n main :: IO () main = mapM_ (putStrLn . fizzBuzz) [1..100] You will craft a fizzbuzz that makes gouts of blood come out of your interviewer’s eye sockets using State. This is a suitable punishment for asking a software candidate to write this in person after presumably getting through a couple phone screens. 4 http://c2.com/cgi/wiki?

This is a suitable punishment for asking a software candidate to write this in person after presumably getting through a couple phone screens. 4 http://c2.com/cgi/wiki?FizzBuzzTest CHAPTER 23. STATE 835 import Control.Monad import Control.Monad.Trans.State fizzBuzz :: Integer -> String fizzBuzz n | n `mod` 15 == 0 = | n `mod` 5 == 0 = | n `mod` 3 == 0 = | otherwise = "FizzBuzz" "Fizz" "Buzz" show n fizzbuzzList :: [Integer] -> [String] fizzbuzzList list = execState (mapM_ addResult list) [] addResult :: Integer -> State [String] () addResult n = do xs <- get let result = fizzBuzz n put (result : xs) main :: IO () main = mapM_ putStrLn $ reverse $ fizzbuzzList [1..100] The good part here is that we’re collecting data initially before dumping the results to standard output via putStrLn.

One of the issues is that we’re accepting an input that defines the numbers we’ll use fizzbuzz on linearly from beginning to end. There are a couple ways we could handle this. One is to use a data structure with cheaper appending to the end. Using (++) recursively can be very slow, so let’s use something that can append in constant time. The counterpart to [] which has this property is the difference list5 which has O(1) append. 5 https://github.com/spl/dlist CHAPTER 23. STATE 836 import Control.Monad import Control.Monad.State import qualified Data.DList as DL fizzBuzz :: Integer -> String fizzBuzz n | n `mod` 15 == 0 = | n `mod` 5 == 0 = | n `mod` 3 == 0 = | otherwise = "FizzBuzz" "Fizz" "Buzz" show n fizzbuzzList :: [Integer] -> [String] fizzbuzzList list = let dlist = execState (mapM_ addResult list) DL.empty in DL.apply dlist [] -- convert back to normal list addResult :: Integer -> State (DL.DList String) () addResult n = do xs <- get let result = fizzBuzz n -- snoc appends to the end, unlike -- cons which adds to the front put (DL.snoc xs result) main :: IO () main = mapM_ putStrLn $ fizzbuzzList [1..100] We can clean this up further.


pages: 560 words: 135,629

Eloquent JavaScript: A Modern Introduction to Programming by Marijn Haverbeke

always be closing, Charles Babbage, domain-specific language, Donald Knuth, en.wikipedia.org, Firefox, fizzbuzz, functional programming, higher-order functions, hypertext link, job satisfaction, MITM: man-in-the-middle, premature optimization, slashdot, web application, WebSocket

Looping a Triangle Write a loop that makes seven calls to console.log to output the following triangle: # ## ### #### ##### ###### ####### It may be useful to know that you can find the length of a string by writing .length after it. let abc = "abc"; console.log(abc.length); // → 3 FizzBuzz Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead. When you have that working, modify your program to print "FizzBuzz" for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those). (This is actually an interview question that has been claimed to weed out a significant percentage of programmer candidates.

Code, and What to Do with It Overview of This Book Typographic Conventions PART I: LANGUAGE 1 VALUES, TYPES, AND OPERATORS Values Numbers Arithmetic Special Numbers Strings Unary Operators Boolean Values Comparison Logical Operators Empty Values Automatic Type Conversion Short-Circuiting of Logical Operators Summary 2 PROGRAM STRUCTURE Expressions and Statements Bindings Binding Names The Environment Functions The console.log Function Return Values Control Flow Conditional Execution while and do Loops Indenting Code for Loops Breaking Out of a Loop Updating Bindings Succinctly Dispatching on a Value with switch Capitalization Comments Summary Exercises Looping a Triangle FizzBuzz Chessboard 3 FUNCTIONS Defining a Function Bindings and Scopes Nested Scope Functions as Values Declaration Notation Arrow Functions The Call Stack Optional Arguments Closure Recursion Growing Functions Functions and Side Effects Summary Exercises Minimum Recursion Bean Counting 4 DATA STRUCTURES: OBJECTS AND ARRAYS The Weresquirrel Data Sets Properties Methods Objects Mutability The Lycanthrope’s Log Computing Correlation Array Loops The Final Analysis Further Arrayology Strings and Their Properties Rest Parameters The Math Object Destructuring JSON Summary Exercises The Sum of a Range Reversing an Array A List Deep Comparison 5 HIGHER-ORDER FUNCTIONS Abstraction Abstracting Repetition Higher-Order Functions Script Data Set Filtering Arrays Transforming with map Summarizing with reduce Composability Strings and Character Codes Recognizing Text Summary Exercises Flattening Your Own Loop Everything Dominant Writing Direction 6 THE SECRET LIFE OF OBJECTS Encapsulation Methods Prototypes Classes Class Notation Overriding Derived Properties Maps Polymorphism Symbols The Iterator Interface Getters, Setters, and Statics Inheritance The instanceof Operator Summary Exercises A Vector Type Groups Iterable Groups Borrowing a Method 7 PROJECT: A ROBOT Meadowfield The Task Persistent Data Simulation The Mail Truck’s Route Pathfinding Exercises Measuring a Robot Robot Efficiency Persistent Group 8 BUGS AND ERRORS Language Strict Mode Types Testing Debugging Error Propagation Exceptions Cleaning Up After Exceptions Selective Catching Assertions Summary Exercises Retry The Locked Box 9 REGULAR EXPRESSIONS Creating a Regular Expression Testing for Matches Sets of Characters Repeating Parts of a Pattern Grouping Subexpressions Matches and Groups The Date Class Word and String Boundaries Choice Patterns The Mechanics of Matching Backtracking The replace Method Greed Dynamically Creating RegExp Objects The search Method The lastIndex Property Looping Over Matches Parsing an INI File International Characters Summary Exercises Regexp Golf Quoting Style Numbers Again 10 MODULES Modules as Building Blocks Packages Improvised Modules Evaluating Data as Code CommonJS ECMAScript Modules Building and Bundling Module Design Summary Exercises A Modular Robot Roads Module Circular Dependencies 11 ASYNCHRONOUS PROGRAMMING Asynchronicity Crow Tech Callbacks Promises Failure Networks Are Hard Collections of Promises Network Flooding Message Routing Async Functions Generators The Event Loop Asynchronous Bugs Summary Exercises Tracking the Scalpel Building Promise.all 12 PROJECT: A PROGRAMMING LANGUAGE Parsing The Evaluator Special Forms The Environment Functions Compilation Cheating Exercises Arrays Closure Comments Fixing Scope PART II: BROWSER 13 JAVASCRIPT AND THE BROWSER Networks and the Internet The Web HTML HTML and JavaScript In the Sandbox Compatibility and the Browser Wars 14 THE DOCUMENT OBJECT MODEL Document Structure Trees The Standard Moving Through the Tree Finding Elements Changing the Document Creating Nodes Attributes Layout Styling Cascading Styles Query Selectors Positioning and Animating Summary Exercises Build a Table Elements by Tag Name The Cat’s Hat 15 HANDLING EVENTS Event Handlers Events and DOM Nodes Event Objects Propagation Default Actions Key Events Pointer Events Mouse Clicks Mouse Motion Touch Events Scroll Events Focus Events Load Event Events and the Event Loop Timers Debouncing Summary Exercises Balloon Mouse Trail Tabs 16 PROJECT: A PLATFORM GAME The Game The Technology Levels Reading a Level Actors Encapsulation as a Burden Drawing Motion and Collision Actor Updates Tracking Keys Running the Game Exercises Game Over Pausing the Game A Monster 17 DRAWING ON CANVAS SVG The Canvas Element Lines and Surfaces Paths Curves Drawing a Pie Chart Text Images Transformation Storing and Clearing Transformations Back to the Game Choosing a Graphics Interface Summary Exercises Shapes The Pie Chart A Bouncing Ball Precomputed Mirroring 18 HTTP AND FORMS The Protocol Browsers and HTTP Fetch HTTP Sandboxing Appreciating HTTP Security and HTTPS Form Fields Focus Disabled Fields The Form as a Whole Text Fields Checkboxes and Radio Buttons Select Fields File Fields Storing Data Client-Side Summary Exercises Content Negotiation A JavaScript Workbench Conway’s Game of Life 19 PROJECT: A PIXEL ART EDITOR Components The State DOM Building The Canvas The Application Drawing Tools Saving and Loading Undo History Let’s Draw Why Is This So Hard?

Exercises Keyboard Bindings Efficient Drawing Circles Proper Lines PART III: NODE 20 NODE.JS Background The node Command Modules Installing with NPM Package Files Versions The File System Module The HTTP Module Streams A File Server Summary Exercises Search Tool Directory Creation A Public Space on the Web 21 PROJECT: SKILL-SHARING WEBSITE Design Long Polling HTTP Interface The Server Routing Serving Files Talks as Resources Long Polling Support The Client HTML Actions Rendering Components Polling The Application Exercises Disk Persistence Comment Field Resets 22 JAVASCRIPT AND PERFORMANCE Staged Compilation Graph Layout Defining a Graph Force-Directed Layout Avoiding Work Profiling Function Inlining Creating Less Garbage Garbage Collection Dynamic Types Summary Exercises Pathfinding Timing Optimizing EXERCISE HINTS Chapter 2: Program Structure Looping a Triangle FizzBuzz Chessboard Chapter 3: Functions Minimum Recursion Bean Counting Chapter 4: Data Structures: Objects and Arrays The Sum of a Range Reversing an Array A List Deep Comparison Chapter 5: Higher-Order Functions Everything Dominant Writing Direction Chapter 6: The Secret Life of Objects A Vector Type Groups Iterable Groups Borrowing a Method Chapter 7: Project: A Robot Measuring a Robot Robot Efficiency Persistent Group Chapter 8: Bugs and Errors Retry The Locked Box Chapter 9: Regular Expressions Quoting Style Numbers Again Chapter 10: Modules A Modular Robot Roads Module Circular Dependencies Chapter 11: Asynchronous Programming Tracking the Scalpel Building Promise.all Chapter 12: Project: A Programming Language Arrays Closure Comments Fixing Scope Chapter 14: The Document Object Model Build a Table Elements by Tag Name The Cat’s Hat Chapter 15: Handling Events Balloon Mouse Trail Tabs Chapter 16: Project: A Platform Game Pausing the Game A Monster Chapter 17: Drawing on Canvas Shapes The Pie Chart A Bouncing Ball Precomputed Mirroring Chapter 18: HTTP and Forms Content Negotiation A JavaScript Workbench Conway’s Game of Life Chapter 19: Project: A Pixel Art Editor Keyboard Bindings Efficient Drawing Circles Proper Lines Chapter 20: Node.js Search Tool Directory Creation A Public Space on the Web Chapter 21: Project: Skill-Sharing Website Disk Persistence Comment Field Resets Chapter 22: JavaScript and Performance Pathfinding Optimizing INDEX For Lotte and Jan “We think we are creating the system for our own purposes.


pages: 1,331 words: 183,137

Programming Rust: Fast, Safe Systems Development by Jim Blandy, Jason Orendorff

bioinformatics, bitcoin, Donald Knuth, duck typing, Elon Musk, Firefox, fizzbuzz, functional programming, mandelbrot fractal, Morris worm, MVC pattern, natural language processing, reproducible builds, side project, sorting algorithm, speech recognition, Turing test, type inference, WebSocket

(spin.next(), Some(&"East")); Or, for a really gratuitous use of iterators: use std::iter::{once, repeat}; let fizzes = repeat("").take(2).chain(once("fizz")).cycle(); let buzzes = repeat("").take(4).chain(once("buzz")).cycle(); let fizzes_buzzes = fizzes.zip(buzzes); let fizz_buzz = (1..100).zip(fizzes_buzzes) .map(|tuple| match tuple { (i, ("", "")) => i.to_string(), (_, (fizz, buzz)) => format!("{}{}", fizz, buzz) }); for line in fizz_buzz { println!("{}", line); } This plays a children’s word game, now sometimes used as a job interview question for coders, in which the players take turns counting, replacing any number divisible by three with the word “fizz”, and any number divisible by five with “buzz”. Numbers divisible by both become “fizzbuzz”. Consuming Iterators So far we’ve covered creating iterators, and adapting them into new iterators; here we finish off the process by showing ways to consume them.