Bonfire: Sum All Numbers in a Range

The Challenge:
We’ll pass you an array of two numbers. Return the sum of those two numbers and all numbers between them.

The lowest number will not always come first.

Helpful Links:
Array.reduce()
Math.min()
Math.max()


My Solution:

function sumAll(arr) {
  var highestNum = Math.max.apply(null, arr);
  var lowestNum = Math.min.apply(Math, arr);
  var numArr = [];
  for (var i = lowestNum; i <= highestNum; i++) {
    numArr.push(i);
  }
  console.log(numArr);
  var sumNum = numArr.reduce(function(previousValue, currentValue, currentIndex, array) {
    return previousValue + currentValue;
  });
  return sumNum;
}

sumAll([1, 4]);

To approach this challenge, I broke it down into small pieces.

1. First I knew I had to get the highest number, so I used the helpful hint of Math.max() to find a way to grab the highest number from the given array.

Because the given numbers are inside of an array, just using Math.max(arr) wouldn’t work. I had to use Math.max.apply(null, arr) to get the highest number.

2. Now that I had the highest number, I needed to find the lowest number in an array.  I used Math.min.apply(Math, arr);

3. I then created a for loop to get all the numbers between my lowest number and my highest number, inclusive.

Advertisements

Deploy Sinatra app on Heroku

This is for everyone who has finished their Sinatra application and wants to deploy it on Heroku.

FYI::You will need to have all your files uploaded on your Github repo to be able to deploy on Heroku. The following steps are assuming you have deployed to Heroku before. If you haven’t, follow this excellent tutorial.

Example app name: Hangman
app file: game/hangman.rb

Steps:

1. Create a Gemfile in your app directory that has the following:
The file path should look something like this: game/Gemfile where ‘game’ is the name of your app directory

source 'https://rubygems.org'
gem 'sinatra'
gem 'sinatra-contrib'

Be sure it list ALL gems you use in this Gemfile otherwise Heroku will give you an H10 – App Crashed error.

2. Create a config.ru file in your app directory:
The file path should look something like this: game/config.ru

require './hangman'
run Sinatra::Application

3. In your app file (ie. hangman.rb), require Sinatra:

require 'sinatra'

If you don’t have any content in the file, create a simple Hello World by adding the following below your require statement:

get '/' do
  "Hello World!"
end

4. Run Bundle Update
In your terminal (or Command Prompt):

$ bundle update

This will create and update your Gemfile.lock.
You can also manually create a Gemfile.lock and run bundle update after.

5. Commit your new files to Github and push to Heroku!

$ git add config.ru Gemfile Gemfile.lock
$ git commit -m "adding Heroku deployment files"
$ git push origin master
$ git push heroku master