• Activity
  • Votes
  • Comments
  • New
  • All activity
  • Showing only topics in ~comp with the tag "coding". Back to normal view / Search all groups
    1. Code Quality Tip: Wrapping external libraries.

      Preface Occasionally I feel the need to touch on the subject of code quality, particularly because of the importance of its impact on technical debt, especially as I continue to encounter the...

      Preface

      Occasionally I feel the need to touch on the subject of code quality, particularly because of the importance of its impact on technical debt, especially as I continue to encounter the effects of technical debt in my own work and do my best to manage it. It's a subject that is unfortunately not emphasized nearly enough in academia.


      Background

      As a refresher, technical debt is the long-term cost of the design decisions in your code. These costs can manifest in different ways, such as greater difficulty in understanding what your code is doing or making non-breaking changes to it. More generally, these costs manifest as additional time and resources being spent to make some kind of change.

      Sometimes these costs aren't things you think to consider. One such consideration is how difficult it might be to upgrade a specific technology in your stack. For example, what if you've built a back-end system that integrates with AWS and you suddenly need to upgrade your SDK? In a small project this might be easy, but what if you've built a system that you've been maintaining for years and it relies heavily on AWS integrations? If the method names, namespaces, argument orders, or anything else has changed between versions, then suddenly you'll need to update every single reference to an AWS-related tool in your code to reflect those changes. In larger software projects, this could be a daunting and incredibly expensive task, spanning potentially weeks or even months of work and testing.

      That is, unless you keep those references to a minimum.


      A Toy Example

      This is where "wrapping" your external libraries comes into play. The concept of "wrapping" basically means to create some other function or object that takes care of operating the functions or object methods that you really want to target. One example might look like this:

      <?php
      
      class ImportedClass {
          public function methodThatMightBecomeModified($arg1, $arg2) {
              // Do something.
          }
      }
      
      class ImportedClassWrapper {
          private $class_instance = null;
      
          private function getInstance() {
              if(is_null($this->class_instance)) {
                  $this->class_instance = new ImportedClass();
              }
      
              return $this->class_instance;
          }
      
          public function wrappedMethod($arg1, $arg2) {
              return $this->getInstance()->methodThatMightBecomeModified($arg1, $arg2);
          }
      }
      
      ?>
      

      Updating Tools Doesn't Have to Suck

      Imagine that our ImportedClass has some important new features that we need to make use of that are only available in the most recent version, and we're several versions behind. The problem, of course, is that there were a lot of changes that ended up being made between our current version and the new version. For example, ImportedClass is now called NewImportedClass. On top of that, methodThatMightBecomeModified is now called methodThatWasModified, and the argument order ended up getting switched around!

      Now imagine that we were directly calling new ImportedClass() in many different places in our code, as well as directly invoking methodThatMightBecomeModified:

      <?php
      
      $imported_class_instance = new ImportedClass();
      $imported_class_instance->methodThatMightBeModified($val1, $val2);
      
      ?>
      

      For every single instance in our code, we need to perform a replacement. There is a linear or--in terms of Big-O notation--a complexity of O(n) to make these replacements. If we assume that we only ever used this one method, and we used it 100 times, then there are 100 instances of new ImportClass() to update and another 100 instances of the method invocation, equaling 200 lines of code to change. Furthermore, we need to remember each of the replacements that need to be made and carefully avoid making any errors in the process. This is clearly non-ideal.

      Now imagine that we chose instead to use the wrapper object:

      <?php
      
      $imported_class_wrapper = new ImportedClassWrapper();
      $imported_class_wrapper->wrappedMethod($val1, $val2);
      
      ?>
      

      Our updates are now limited only to the wrapper class:

      <?php
      
      class ImportedClassWrapper {
          private $class_instance = null;
      
          private function getInstance() {
              if(is_null($this->class_instance)) {
                  $this->class_instance = new NewImportedClass();
              }
      
              return $this->class_instance;
          }
      
          public function wrappedMethod($arg1, $arg2) {
              return $this->getInstance()->methodThatWasModified($arg2, $arg1);
          }
      }
      
      ?>
      

      Rather than making changes to 200 lines of code, we've now made changes to only 2. What was once an O(n) complexity change has now turned into an O(1) complexity change to make this upgrade. Not bad for a few extra lines of code!


      A Practical Example

      Toy problems are all well and good, but how does this translate to reality?

      Well, I ran into such a problem myself once. Running MongoDB with PHP requires the use of an external driver, and this driver provides an object representing a MongoDB ObjectId. I needed to perform a migration from one hosting provider over to a new cloud hosting provider, with the application and database services, which were originally hosted on the same physical machine, hosted on separate servers. For security reasons, this required an upgrade to a newer version of MongoDB, which in turn required an upgrade to a newer version of the driver.

      This upgrade resulted in many of the calls to new MongoId() failing, because the old version of the driver would accept empty strings and other invalid ID strings and default to generating a new ObjectId, whereas the new version of the driver treated invalid ID strings as failing errors. And there were many, many cases where invalid strings were being passed into the constructor.

      Even after spending hours replacing the (literally) several dozen instances of the constructor calls, there were still some places in the code where invalid strings managed to get passed in. This made for a very costly upgrade.

      The bugs were easy to fix after the initial replacements, though. After wrapping new MongoId() inside of a wrapper function, a few additional conditional statements inside of the new function resolved the bugs without having to dig around the rest of the code base.


      Final Thoughts

      This is one of those lessons that you don't fully appreciate until you've experienced the technical debt of an unwrapped external library first-hand. Code quality is an active effort, but a worthwhile one. It requires you to be willing to throw away potentially hours or even days of work when you realize that something needs to change, because you're thinking about how to keep yourself from banging your head against a wall later down the line instead of thinking only about how to finish up your current task.

      "Work smarter, not harder" means putting in some hard work upfront to keep your technical debt under control.

      That's all for now, and remember: don't be fools, wrap your external tools.

      23 votes
    2. Programming Challenge: Shape detection.

      The programming challenges have kind of come to a grinding halt recently. I think it's time to get another challenge started! Given a grid of symbols, representing a simple binary state of...

      The programming challenges have kind of come to a grinding halt recently. I think it's time to get another challenge started!

      Given a grid of symbols, representing a simple binary state of "filled" or "unfilled", determine whether or not a square is present on the grid. Squares must be 2x2 in size or larger, must be completely solid (i.e. all symbols in the NxN space are "filled"), and must not be directly adjacent to any other filled spaces.

      Example, where 0 is "empty" and 1 is "filled":

      000000
      011100
      011100
      011100
      000010
      
      // Returns true.
      
      000000
      011100
      011100
      011110
      000000
      
      // Returns false.
      
      000000
      011100
      010100
      011100
      000000
      
      // Returns false.
      

      For those who want a greater challenge, try any of the following:

      1. Get a count of all squares.
      2. Detect squares that are touching (but not as a rectangle).
      3. Detect other specific shapes like triangles or circles (you will need to be creative).
      4. If doing (1) and (3), count shapes separately based on type.
      5. Detect shapes within unfilled space as well (a checkerboard pattern is a great use case).
      13 votes
    3. Light Analysis of a Recent Code Refactor

      Preface In a previous topic, I'd covered the subject of a few small lessons regarding code quality. Especially important was the impact on technical debt, which can bog down developer...

      Preface

      In a previous topic, I'd covered the subject of a few small lessons regarding code quality. Especially important was the impact on technical debt, which can bog down developer productivity, and the need to pay down on that debt. Today I would like to touch on a practical example that I'd encountered in a production environment.


      Background

      Before we can discuss the refactor itself, it's important to be on the same page regarding the technologies being used. In my case, I work with PHP utilizing a proprietary back-end framework and MongoDB as our database.

      PHP is a server-side scripting language. Like many scripting languages, it's loosely typed. This has some benefits and drawbacks.

      MongoDB is a document-oriented database. By default it's schema-less, allowing you to make any changes at will without an update to schema. This can blend pretty well with the loose typing of PHP. Each document is represented using a JSON-like structure and is stored in something called a "collection". For those of you accustomed to using relational database, a "collection" is analogous to a table, each document is a row, and each field in the document is a column. A typical query in the MongoDB shell would look something like this:

      db.users.findOne({
          username: "Emerald_Knight"
      });
      

      The framework itself has some framework-specific objects that are held in global references. This makes them easily accessible, but naturally littering your code with a bunch of globals is both error-prone and an eyesore.


      Unexpected Spaghetti

      In my code base are a number of different objects that are designed to handle basic CRUD-like operations on their associated database entries. Some of these objects hold references to other objects, so naturally there is some data validation that occurs to ensure that the references are both valid and authorized. Pretty typical stuff.

      What I noticed, however, is that the collection names for these database entries were littered throughout my code. This isn't necessarily a bad thing, except there were some use cases that came to mind: what if it turned out that my naming for one or more of these collections wasn't ideal? What if I wanted to change a collection name for the sake of easier management on the database end? What if I have a tendency to forget the name of a database collection and constantly have to look it up? What if I make a typo of all things? On top of that, the framework's database object was stored in a global variable.

      These seemingly minor sources of technical debt end up adding up over time and could cause some serious problems in the worst case. I've had breaking bugs make their way passed QA in the past, after all.


      Exchanging Spaghetti for Some Light Lasagna

      The problem could be characterized simply: there were scoping problems and too many references to what were essentially magic strings. The solution, then, was to move the database object reference from global to local scope within the application code and to eliminate the problem of magic strings. Additionally, it's a good idea to avoid polluting the namespace with an over-reliance on constants, and using those constants for database calls can also become unsightly and difficult to follow as those constants could end up being generally disconnected from the objects they're associated with.

      There turned out to be a nice, object-oriented, very PHP-like solution to this problem: a so-called "magic method" named "__call". This method is invoked whenever an "inaccessible" method is called on the object. Using this method, a database command executed on a non-database object could pass the command to the database object itself. If this logic were placed within an abstract class, the collection could then be specified simply as a configuration option in the inheriting class.

      This is what such a solution could look like:

      <?php
      
      abstract class MyBaseObject {
      
          protected $db = null;
          protected $collection_name = null;
      
          public function __construct() {
              global $db;
              
              $this->db = $db;
          }
      
          public function __call($method_name, $args) {
              if(method_exists($this->db, $method_name)) {
                  return $this->executeDatabaseCommand($method_name, $args);
              }
      
              throw new Exception(__CLASS__ . ': Method "' . $method_name . '" does not exist.');
          }
      
          public function executeDatabaseCommand($command, $args) {
              $collection = $this->collection_name;
              $db_collection = $this->db->$collection;
      
              return call_user_func_array(array($db_collection, $command), $args);
          }
      }
      
      class UserManager extends MyBaseObject {
          protected $collection_name = 'users';
      
          public function __construct() {
              parent::__construct();
          }
      }
      
      $user_manager = new UserManager();
      $my_user = $user_manager->findOne(array('username'=>'Emerald_Knight'));
      
      ?>
      

      This solution utilizes a single parent object which transforms a global database object reference into a local one, eliminating the scope issue. The collection name is specified as a class property of the inheriting object and only used in a single place in the parent object, eliminating the magic string and namespace polluting issues. Any time you perform queries on users, you do so by using the UserManager class, which guarantees that you will always know that your queries are being performed on the objects that you intend. And finally, if the collection name for an object class ever needs to be updated, it's a simple matter of modifying the single instance of the class property $collection_name, rather than tracking down some disconnected constant.


      Limitations

      This, of course, doesn't solve all of the existing problems. After all, executing the database queries for one object directly from another is still pretty bad practice, violating the principle of separation of concerns. Instead, those queries should generally be encapsulated within object methods and the objects themselves given primary responsibility in handling associated data. It's also incredibly easy to inadvertently override a database method, e.g. defining a findOne() method on UserManager, so there's still some mindfulness required on the part of the programmer.

      Still, given the previous alternative, this is a pretty major improvement, especially for an initial refactor.


      Final Thoughts

      As always, technical debt is both necessary and inevitable. After all, in exchange for not taking the excess time and considering structuring my code this way in the beginning, I had greater initial velocity to get the project off of the ground. What's important is continually reviewing your code as you're building on top of it so that you can identify bottlenecks as they begin to strain your efficiency, and getting those bottlenecks out of the way.

      In other words, even though technical debt is often necessary and is certainly inevitable, it's important to pay down on some of that debt once it starts getting expensive!

      7 votes
    4. Programming Challenge: Polygon analysis.

      It's time for another programming challenge! Given a list of coordinate pairs on a 2D plane that describe the vertices of a polygon, determine whether the polygon is concave or convex. Since a...

      It's time for another programming challenge!

      Given a list of coordinate pairs on a 2D plane that describe the vertices of a polygon, determine whether the polygon is concave or convex.

      Since a polygon could potentially be any shape if we don't specify which vertices connect to which, we'll assume that the coordinates are given in strict order such that adjacent coordinates in the list are connected. Specifically, if we call the list V[1, n] and say that V[i] <-> V[j] means "vertex i and vertex j are connected", then for each arbitrary V[i] we have V[i-1] <-> V[i] <-> V[i+1]. Moreover, since V[1] and V[n] are at the ends of the list, V[1] <-> V[n] holds (i.e. the list "wraps around").

      Finally, for simplicity we can assume that all coordinates are unique, that all polygon descriptions generate valid polygons with 3 or more non-overlapping sides, and that, yes, we're working with coordinates that exist in the set of real numbers only. Don't over-complicate it :)

      For those who want an even greater challenge, extend this out to work with 3D space!

      8 votes
    5. Programming Challenge: Reverse Polish Notation Calculator

      It's been nearly a week, so it's time for another programming challenge! This time, let's create a calculator that accepts reverse Polish notation (RPN), also known as postfix notation. For a bit...

      It's been nearly a week, so it's time for another programming challenge!

      This time, let's create a calculator that accepts reverse Polish notation (RPN), also known as postfix notation.

      For a bit of background, RPN is where you take your two operands in an expression and place the operator after them. For example, the expression 3 + 5 would be written as 3 5 +. A more complicated expression like (5 - 3) x 8 would be written as 5 3 - 8 x, or 8 5 3 - x.

      All your program has to do is accept a valid RPN string and apply the operations in the correct order to produce the expected result.

      18 votes
    6. Programming Challenge: Counting isolated regions.

      Another week, another challenge! This time, assume you're given a grid where each . represents an empty space and each # represents a "wall". We'll call any contiguous space of .s a "region". You...

      Another week, another challenge!

      This time, assume you're given a grid where each . represents an empty space and each # represents a "wall". We'll call any contiguous space of .s a "region". You can also think of a grid with no walls the "base" region. The walls may subdivide the base region into any number of isolated sub-regions of any shape or size.

      Write a program that will, given a grid description, compute the total number of isolated regions.

      For example, the following grid has 5 isolated regions:

      ....#....#
      ....#.###.
      ....#.#.#.
      #...#..#..
      .#..#...#.
      
      16 votes
    7. Programming Challenge: Merge an arbitrary number of arrays in sorted order.

      It looks like it's been over a week and a half since our last coding challenge, so let's get one going. This challenge is a relatively simple one, but it's complex enough that you can take a...

      It looks like it's been over a week and a half since our last coding challenge, so let's get one going. This challenge is a relatively simple one, but it's complex enough that you can take a variety of different approaches to it.

      As the title suggests, write a program that accepts an arbitrary number of arrays, in whatever form or manner you see fit (if you want to e.g. parse a potentially massive CSV file, then go nuts!), and returns a single array containing all of the elements of the other arrays in sorted order. That's it!

      Bonus points for creative, efficient, or generalized solutions!

      24 votes
    8. Programming Challenge: Compute the shortest path to visit all target spots on a grid.

      Let's do something a little more challenging this time. Given an MxN grid of arbitrary size, and given a random starting place on that grid and a list of points to visit, find the shortest path...

      Let's do something a little more challenging this time.

      Given an MxN grid of arbitrary size, and given a random starting place on that grid and a list of points to visit, find the shortest path such that you visit all of them. Path lengths will be computed using taxicab distances rather than strict coordinate distance calculations.

      There are no restrictions on expected input this time. Output should be the total distance traveled between points.


      Example

      Assume that we use the character # to denote a spot on the grid, the character @ to denote your starting point, and the character * to denote a place on the grid that you're required to visit. One such grid may look something like this:

      ######
      ######
      **####
      #*####
      #*#*##
      #@####
      ######
      

      In this case, let's say that the bottom-left point on the grid is point (0, 0) and we're starting on point (1, 1). One valid solution would be to move to point (3, 2), then (1, 2), then (1, 3), then (1, 4), and finally (0, 4). The shortest path available is thus 8. Note that it's not enough just to visit the next nearest point on the grid!

      15 votes
    9. Programming Mini-Challenge: KnightBot

      Another programming mini-challenge for you. It's been a month since the first one and that seemed to be rather successful. (I appreciate that there are other challenges on here but trying to sync...

      Another programming mini-challenge for you. It's been a month since the first one and that seemed to be rather successful. (I appreciate that there are other challenges on here but trying to sync with them seems tricky!)

      A reminder:
      I'm certain that many of you might find these pretty straight forward, but I still think there's merit in sharing different approaches to simple problems, including weird-and-wonderful ones.


      KnightBot


      Info

      You will be writing a small part of a Chess program, specifically focusing on the Knight, on an 8 x 8 board.


      Input

      The top-left square of the board will have index 0, and the bottom-right square will have index 63.

      • The first input is the starting square of the knight.
      • The second input is the requested finishing square of the knight.
      • The third input is the number of maximum moves allowed.

      Output

      The expected outcome is either True or False, determined by whether or not the Knight can reach the requested finishing square within the number of allowed moves when stating on the starting square.

      e.g. The expected output for the input 16, 21, 4 is True since the Knight can move 16->33->27->21, which is 3 moves.
      

      Extensions

      Some additional ideas for extending this challenge...

      1. Instead of an 8x8, what if the board was nxn?
      2. Instead of "within x moves", what if it was "with exactly x moves?"
      3. Instead of a traditional Knight's move (2 long, 1 short), what if it was n long and m short?
      4. What if the board was infinite?
      5. What if the board looped back around when crossing the edges? (e.g. the square to the right of 7 is 0)
      17 votes
    10. Coding Noob Needs Help/Guidance on Small Project

      Hi, There's a certain site which hosts media files and has a player that depends on a lot of third-party resources to play, while browsers have native support for those file types. Those 3rd-party...

      Hi,

      There's a certain site which hosts media files and has a player that depends on a lot of third-party resources to play, while browsers have native support for those file types. Those 3rd-party resources are often blocked by ad blockers and I have no desire to white-list them. I would like to extract the direct link to the media file and make it playable on my custom web page.

      The link to the media file is present in the page source of each page, always on the same line. It's not anchored in HTML but present in the JavaScript for the player, like so:

          $(document).ready(function(){
            $("#jquery_jplayer_1").jPlayer({
              ready: function () {
                $(this).jPlayer("setMedia", {
                  [ext]: "https://[domain]/[filename.ext]"
                });
              },
      

      In this example it's on line #5. [ext] = the file extension.

      I want to build the following:

      • A web page with a form with a single input field meant to receive links from that specific file host
      • [Something] that extracts the file link from the source of the host's page
      • Present the linked file as playable in an embedded native player

      So far I've managed to create a form with an input box and a submit button, but it doesn't do anything yet. What is the best way to build the actual functionality? I know HTML/CSS. I have some rudimentary understanding of JavaScript/jQuery and Python3, so those would be my preferred tools.

      For those worried about piracy: The files in question are not copyrighted and I'm not looking to make copies. I just want to make them playable. This is for personal use.

      Thank you for reading this far. Any and all advice is welcome!

      10 votes
    11. What are your unsolved programming problems?

      I thought it could be fun to discuss problems that we've encountered in our programming or programming-related work and have never found a solution for. I figure that at worst we can have a lot of...

      I thought it could be fun to discuss problems that we've encountered in our programming or programming-related work and have never found a solution for. I figure that at worst we can have a lot of fun venting about and scratching our heads at things that just don't make any sense to anyone, and at best we might be able to help each other find answers and, more importantly, some closure.

      16 votes
    12. Inexperienced Programming Question

      TLDR: What programming language would be useful for taking info in an excel file and producing a text file (that is organized and arranged in a particular way) containing that info? Which would be...

      TLDR: What programming language would be useful for taking info in an excel file and producing a text file (that is organized and arranged in a particular way) containing that info? Which would be useful for this problem but also helpful in general? And also, are there any recommended online courses where I could learn it?


      I have no real experience coding or anything but have always wanted to learn. Recently at work we've encountered a problem. My boss had created a matlab program in order to take text/numbers from an excel document and transfer them to a text file, but in an organized way.

      Say you have something you call "Pancakes" and the cell next to it has the number "3", as in there are three pancakes. I want to be able to create a text file that would read something like this:

      NUMBER OF PANCAKES

      • Pancakes: 3

      We recently have changed around the format of the excel document for a different item, for example "French Toast". I've tried to mess with matlab briefly but was unable to change the program to compensate, and I no longer easily have access to matlab.

      I'm seeing this as an opportunity to learn some programming and also fix some stuff at work. So what programming language would be useful for fixing this problem? Which would be useful for this problem, but also helpful in general? And also, are there any recommended online courses where I could learn it?

      Thanks for any help, I appreciate it.

      16 votes
    13. Programming Challenge: Make a game in 1 hour!

      Background There's been some talk on ~ before, and it seems like there are quite a few people who are either interested in, learning, or working in game development, so I thought this could be a...

      Background

      There's been some talk on ~ before, and it seems like there are quite a few people who are either interested in, learning, or working in game development, so I thought this could be a fun programming challenge.

      This one is fairly open-ended: make a game in 1 hour. Any game, any engine, don't worry about art or sound or anything.

      Doing is the best way to learn. Most people's first project is something overly ambitious, and when they find that it's more difficult than they thought, they can get discouraged, or even give up entirely. This is why the 1 hour limit is important: it forces you to finish something, even if it's small. When you're done, you can come out of it saying you made a game, and you learned from it.

      Chances are the game might not be fun, look bad, be buggy, etc. But don't worry about that, everyone's game will have problems, and if you do create something really fun or innovative, congratulations, you have a prototype that you can expand on later!

      "Rules"

      Like I said before, these "rules" are pretty simple: make a game in (approximately) 1 hour. You can use any tools you want. If you use external assets (art, sound), it's probably best you use something you have the rights to (see resources). If you're completely new to game development/programming, your goal could even be to finish a tutorial.

      If you're the kind of person who tends to get carried away with these things, you might want to post a comment saying you're starting, then another one once you've finished your game.

      Please share your finished game, I'm sure everyone would love to try them! If your game is web-based, it can be hosted for free on Github Pages or Itch.io. If downloadable, it can be hosted for free on Google Drive, Mega, Dropbox, Itch.io, etc.

      Resources

      Engines

      If you're a beginner, a good engine to start with is LÖVE. It's very simple, and uses Lua, which is very easy to learn.

      If you're familiar with another language, you could use a library to make it in that language. Some examples:

      C++: SFML, SDL, Allegro

      Javascript: kontra, Phaser, pixi.js

      Python: pygame

      Rust: Piston, ggez, Amethyst

      If you want something more complex, consider Godot, Unity, or Unreal.

      You can also try something visual like Construct, Clickteam Fusion, or GDevelop

      Art

      For such a short time constraint, I'd suggest you use your own "programmer art": just use some basic shapes. Your primary focus should be gameplay.

      If you think you have time to find something, try looking on OpenGameArt.

      Sound

      You can make simple sound effects very quickly with sfxr (or in this case, a web port of sfxr called jsfxr).

      27 votes
    14. Programming Mini-Challenge: TicTacToeBot

      I've seen the programming challenges on ~comp as well as quite a few users who are interested in getting started with programming. I thought it would be interesting to post some 'mini-challenges'...

      I've seen the programming challenges on ~comp as well as quite a few users who are interested in getting started with programming. I thought it would be interesting to post some 'mini-challenges' that all could have a go at. I'm certain that many of you might find these pretty straight forward, but I still think there's merit in sharing different approaches to simple problems, including weird-and-wonderful ones.

      This is my first post and I'm a maths-guy who dabbles in programming, so I'm not promising anything mind-blowing. If these gain any sort of traction I'll post some more.

      Starting of with...


      TicTacToeBot


      Info

      You will be writing code for a programme that will check to see if a player has won a game of tic-tac-toe.


      Input

      The input will be 9 characters that denote the situation of each square on the grid.

      • 'X' represents the X-player has moved on that square.
      • 'O' represents the O-player has moved on that square.
      • '#' represents that this square is empty.

      Example:

      |O| |X|
      |X|X|O|    The input for this grid will be O#XXXOO##
      |O| | |
      

      Output

      The expected output is the character representing the winning player, or "#" if the game is not won.

      (e.g. The expected output for the example above is '#' since no player has won)


      29 votes
    15. Programming Challenge: creative FizzBuzz

      Pretty standard: 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...

      Pretty standard:

      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”.

      The twist: come up with the most creative or unusual way to solve this in your language of choice.

      39 votes
    16. Programming Challenge: Freestyle textual analysis.

      I just realized that I completely glossed over this week's programming challenge. For this week, let's do something more flexible: write a program that accepts a file as input--either through a...

      I just realized that I completely glossed over this week's programming challenge. For this week, let's do something more flexible: write a program that accepts a file as input--either through a file name/path or through standard input--and perform any form of analysis you want on its contents. That's it!

      For instance, you could count the occurrences of each word and find the most common ones, or you could determine the average sentence length, or the average unique words per sentence. You could even perform an analysis on changes in words and sentence structure over time (could be useful for e.g. poetry where metre may play an important role). You can stick with simple numbers or dive right into the grittiest forms of textual analysis currently available. You could output raw text or even a graphical representation. You could even do a bit of everything!

      How simple or complex your solution ends up being is completely up to you, but I encourage you to challenge yourself by e.g. learning a new language or about different textual analysis techniques, or by focusing on code quality rather than complexity, or even by taking a completely different approach to the problem than you ordinarily would. There are a lot of learning opportunities available here.

      11 votes
    17. Programming Challenge: Construct and traverse a binary tree.

      It's that time of week again! For this week's programming challenge, I thought I would focus on data structures. Goal: Construct a binary tree data structure. It may handle any data type you...

      It's that time of week again! For this week's programming challenge, I thought I would focus on data structures.

      Goal: Construct a binary tree data structure. It may handle any data type you choose, but you must handle sorting correctly. You must also provide a print function that prints each value in the tree on a new line, and the values must be printed in strictly increasing order.

      If you're unfamiliar with this data structure, it's a structure that starts with a single "root" node, and this root can have a left child, right child, both, or neither. Each of these child nodes is exactly the same as the root node, except the root has no parent. This branching structure is why it's called a tree. Furthermore, left descendants always have values smaller than the parent, and right descendants always have larger values.

      12 votes
    18. Programming Challenge: Given a triangle of numbers, find the path from the top to the bottom of the triangle with the largest sum.

      This problem is based on the Project Euler problem here. Goal: Given some input describing a triangle of numbers, find the path starting from the top-most row of the triangle and ending at the...

      This problem is based on the Project Euler problem here.

      Goal: Given some input describing a triangle of numbers, find the path starting from the top-most row of the triangle and ending at the bottom-most row of the triangle that contains the largest sum of all of the numbers along the path. You may only move downward and you must select an adjacent position to move to. Efficiency is not a requirement for completion.

      Constraints:

      • The first line of input for a triangle will be a single integer telling you how many rows the triangle will have.
      • Each following line of input will be the next row of the number triangle, starting at the first row.
      • For each line describing the number triangle, the individual numbers will be separated by a single space.

      Note: The constraints above are to keep hard-coded triangles out of submitted solutions while also ensuring that all languages can equally handle this problem without annoying workarounds for lower-level languages. The consistency also makes it easier for beginners to review and understand someone else's code, and makes it easier to receive help if you get stuck. They're not necessarily required, but are highly encouraged.

      Example input:

      4
      1
      3 2
      4 5 6
      7 8 9 10
      

      Corresponding triangle:

         1
        3 2
       4 5 6
      7 8 9 10
      

      Expected result: 19 (1 + 2 + 6 + 10)

      Extra Credit: As noted on the Project Euler page, you can solve this using a brute force method, but it's incredibly inefficient. Specifically, a brute force solution would be O(2n) time (exponential). There exists a solution that can be solved in O(n2) time (quadratic). Find this solution.

      13 votes
    19. Most instructive/well made educational computer science/math videos?

      What are some of your favorite videos that explain deep topics in depth? I've recently been on a 3blue1brown binge (youtube) and am looking for more videos of that ilk. Doesn't have to be a series...

      What are some of your favorite videos that explain deep topics in depth?

      I've recently been on a 3blue1brown binge (youtube) and am looking for more videos of that ilk. Doesn't have to be a series or a consistent uploader, one off videos are sometimes the best. Just thought I'd ask ~comp if there's anything in particular that comes to mind.

      This is in part inspired by the video posted by /u/Deimos in the Technical Goals section of Tildes, titled Simplicity Matters

      11 votes
    20. Anyone got suggestions for coding / gaming headphones?

      By coding headphones I mean with active noise cancellation, to be focused on your work. However I'd like to have it more universal since i do play videogames in my freetime, so with a microphone...

      By coding headphones I mean with active noise cancellation, to be focused on your work. However I'd like to have it more universal since i do play videogames in my freetime, so with a microphone would be best - Or should i have 2 sets for both activities?

      Something below 100€ would be nice (naive yes, but I aint got much).

      I looked at the Mixcder e7 on Amazon, which looked promising. Thoughts?

      9 votes
    21. Programming Challenge: Translate 24-hour time into words

      This is an adapted version of Talking Clock from /r/DailyProgrammer. The point of this thread is to post your code for solving the task. Other will comment with feedback and new ideas. Post what...

      This is an adapted version of Talking Clock from /r/DailyProgrammer.

      The point of this thread is to post your code for solving the task. Other will comment with feedback and new ideas. Post what language (and version, if relevant) your code is written in.

      Task description

      Your task is to translate a 24-hour formatted time to words.

      Input description

      An hour between 00 and 23 followed by a colon followed by a minute between 0 and 59.

      Output description

      The time expressed in words, in 12-hour format followed by "am" or "pm".

      Sample input

      00:00
      01:30
      12:05
      14:01
      

      Sample output

      It's twelve am
      It's one thirty am
      It's twelve oh five pm
      It's two oh one pm
      
      27 votes