How would I solve a coding puzzle with Javascript?

1.5k Views Asked by At

There is a website called Gild.com that has different coding puzzles/challenges for users to do. They can be completed in wide array of languages including Javascript. I am interested in solving these puzzles in Javascript, but I am unsure of the following:

  • How am I supposed to access the input file which is supposed to be passed as an argument?
  • How am I supposed to output the result?

My understanding of Javascript is that it is run from within an HTML page and that output really is only in the form of placing values in the HTML, modifying the DOM, etc. For that reason it is not clear to me how Javascript can be used for solving these types of problems. Can someone who has used Gild before or has some insights into my question suggest how to proceed?

An example of a problem would be: the given input file contains a positive integer, find the sum of all prime numbers smaller than that integer and output it.


EDIT: Some of the solutions below involve using external resources, but on Gild, I am supposed to put my solution in their editor and then submit it that way, like the following picture shows:

enter image description here

In other words, I don't think my solution can have access to Node.js or other external resources.


Edit: Here are some interesting articles that I have found that I think are the answer to my question:

2

There are 2 best solutions below

2
On BEST ANSWER

I haven't spent much time on Gild, but I do a lot of similar types of problems on Project Euler. I think the best way to go is probably Node.js.

If you're not familiar, Node is basically server-side JavaScript that runs in Google's V8 engine. Installing it on your own Mac/Windows machine takes about 2 minutes. It's also really fast (considering it's JavaScript).

And you'd use it like this:

var fs = require('fs'); // the filesystem module
var contents = fs.readFileSync('theFile.txt', 'utf-8');
// Do stuff with the file contents...

Everything after those first two lines can be done with the same JS you'd write in the browser, right down to calling console.log() to spit out the answer.

So, if you wrote your script in a file on your desktop called getprimes.js, you'd open up your terminal and enter node ~/Desktop/getprimes.js (assuming you're on a Mac)

1
On

If you're:

  1. on a Mac,
  2. planning to do a lot of these puzzles, and
  3. willing to pay $10, then

I highly recommend CodeRunner. It encapsulates runtimes for a variety of languages — from C to JavaScript — and lets you quickly build and run any sort of one-off code. Just hack together your code, ⌘R, and the results are printed right there in the same window.

I haven't used any file-based JavaScript in CodeRunner, but I imagine kennis's suggestions would apply. To output your results:

console.log(...)

Easy as pie!