Quotes help make search much faster. Example: "Practice Makes Perfect"

Thursday, January 31, 2013

Codecademy: String Rotation


// Sample solution

// Write a string rotation method.
// It should pass all the tests given below.
String.prototype.rotate = function(number) {
    /* your code  */
    if(number===0 || number===this.length){
    return this;
    } else if(this.length>Math.abs(number)){
    if(number<0){
    number = Math.abs(number)+1;
    }
    } else if(this.length<Math.abs(number)){
    if(number>0){
    number = (Math.abs(number) % this.length)+2;
    } else {
    number = (Math.abs(number) % this.length)+1;
    }
    }
    var temp1 = this.substring(0,number-1);
    var temp2 = this.substring(number-1,this.length);
    return temp2+temp1; // return rotated string
};

/*********** Tests for your method ***********/
// The comments tell you the expected results.
// The correctness test will run all these tests, so even if you
// delete the lines below, you will still see error messages
// as long as your code doesn't pass all the tests.

console.log("ryEve".rotate(3));        // "Every"

// Zero rotation: no change
console.log("JavaScript".rotate(0));   // "JavaScript"

// Negative numbers: rotate the other way
console.log("mmerprogra".rotate(-4));  // "programmer"

// Rotate by length: no change
console.log("should".rotate(6));       // "should"
console.log("know".rotate( -4));       // "know"

// Larger than length: rotate by modulo
console.log("outab".rotate(22));       // "about"
// (actually the same as "outab".rotate(2); )
console.log("otypesprot".rotate(-36)); // "prototypes"
// (actually the same as "otypesprot".rotate(-6); )

Codecademy: String Reversal - Part 3


// Sample solution

// Change this function so as to reverse strings.
// When given argument "Hello", it should return "olleH".
String.prototype.reverse = function(){
    return this.split("").reverse().join("");
}

// test it:
str = "right to left";
console.log(str.reverse());

Codecademy: String Reversal - Part 2


// Sample solution

// Change this function so as to reverse strings.
// When given argument "Hello", it should return "olleH".
function reverse(str) {
    return str.split("").reverse().join("");
}

// test it:
console.log(reverse("right to left"));

Codecademy: Get Rid of the Man in the Middle


// Sample solution to Method Chaining

var date = "2012-03-16";

var converted_date = date.split('-').reverse().join('/');

Codecademy: String Reversal - Part 1


// Sample solution

var date = "2012-03-16";

// split the date by "-"
var date_as_array = date.split('-');

// reverse the order of elements in the array
var reversed_array = date_as_array.reverse();

// convert the reversed array back to a string using
// the join() method with "/" as separator
var converted_date = reversed_array.join('/');

Codecademy: What should I know?


// Sample solution

var phone = {};
phone.addZero = function(number){
var temp = number.toString();
return ('0'+temp);
}

phone.dialNumber = function(number){
var temp = this.addZero(number);
console.log("dialing "+temp);
}

// Let's tell our phone to call some number. If the number is
// "12345", it should print "dialing 012345" to the Console.
phone.dialNumber("12345");

Codecademy: What will I be learning?


// Sample solution

// Read this code
function makeTags(str) {
    return str
        .split(' ')
        .map(
            function(s) {return '<'+s+'>';}
        ).join('');
}

// Can you guess the result of  makeTags("p ul li")?
// Type in your guess, then hit "Run" to check
var myGuess = "<p><ul><li>";

Sunday, January 27, 2013

Math Problems: Function Perfect Square

Question: What is the sum of all positive integers that will allow the evaluated function  f(x) = x^2 + 19x + 130 to be a perfect square?

Answer: 33

Solved using the script below:


console.log("*************************************")
function isInt(value) {
    return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10));
}

function someF(x){
return (x*x)+(19*x)+130;
}
var max=100000;
for(var i=0; i<max; i++){
temp = someF(i);
temp2 = Math.sqrt(temp);
if(isInt(temp2)){
console.log("i:"+i+" someFunc:"+temp+" sqrt:"+temp2);
}
}

Math Problems: Minimize the fraction

Problem:
The task is to minimize the value of the fraction x/f(x) where x is any 3-digit number and f(x) is its digits sum. What is the 3-digit number that satisfies these conditions?

Answer: 199

Solved using the script below


console.log("*************************************")
var min=100;
for(var i=0; i<1000; i++){
if(i>=100){
var temp = i.toString();
var hun = parseInt(temp[0]);
var ten = parseInt(temp[1]);
var one = parseInt(temp[2]);
var digsum = hun+ten+one;
var frac = i/digsum;
if(frac<min){
console.log(i+" "+digsum+" "+frac);
min=frac;
}
}
}
console.log("min is "+min);

Math Problems: Collatz Function

Problem:

The Collatz function is defined as f(n) = 3n+1 for odd values of n and f(n) = n/2 for even values of n. What is the smallest possible value of n for which f^7(n) is equal to 5.

Answer: 17

Solution: Solved using the script below:


console.log("*********************************");
function collatz(x){
if(x%2===0){
return x/2;
}
else{
return (3*x)+1;
}
}
var max=1000;
for(var i=0; i<max; i++){
var temp = collatz(collatz(collatz(collatz(collatz(collatz(collatz(i)))))));
if(temp===5){
console.log("i: "+i+" temp: "+temp);
}
}

Triangle Angles Given All Three Sides

This script will solve for the angles of a triangle given all its sides using the Law of Cosines.

Type in the length of the sides of a triangle:
Side A meters
Side B meters
Side C meters

Compute

Math Problems: Sum of two-digit numbers

Question:

If we sum all two digit numbers whose digits are made up of combinations of the numbers 1, 2, 3, 4, what is the result?

Answer: 440

Solution: Solved using the script below


console.log("*********************************");
function cati(string, index){
if(string.charAt(index)==='1' || string.charAt(index)==='2' || string.charAt(index)==='3' || string.charAt(index)==='4'){
return true;
}
else {
return false;
}
}

var sum=0;
for(var i=0; i<100; i++){
if(i>=10){
var temp = i.toString();
if(cati(temp,0) && cati(temp,1)){
console.log(temp);
sum+=i;
}
}
}
console.log("Sum is "+sum);

Math Problems: 5-digit Palindromes

Question:

How many five digit palindromes are there?

Answer: 900

Solution: Solved using the script below


console.log("*********************************");
var count=0;
for(var i=0; i<100000; i++){
if(i>=10000){
var temp = i.toString();
if(temp.charAt(0)===temp.charAt(4) && temp.charAt(1)===temp.charAt(3)){
console.log(temp);
count++;
}
}
}
console.log("Count is "+count);

How do you type the INTERSECTION logic symbol in Windows?

Answer: ALT + 239

Math Problems: Union and Intersection

Problem:

If set A has X elements, set B has Y elements and A U B (read A union B) has Z elements, how many elements does A ∩ B (read A intersection B) have?

Answer:

Since

A U B = A + B - (A ∩ B)

Then,

A ∩ B = A + B - (A U B)
elements in A ∩ B = X + Y - Z

Import Your Modules


# Codecademy Sample Solution

from urllib2 import urlopen
from json import load

Saturday, January 26, 2013

Limit By Date Range


# Codecademy Sample Solution

import requests
import pprint

query_params = { 'apikey': '24115b5bd3d34ed28fc03a8c53eed18c',
'per_page': 3,
   # ...
  'phrase': 'holiday season',
  'start_date': '2012-11-01',
  'end_date': '2012-12-31'
}

endpoint = 'http://capitolwords.org/api/text.json'

response = requests.get(endpoint, params=query_params)

data = response.json
pprint.pprint(data)

Filterning By State


# Codecademy Sample Solution

import requests
import pprint

query_params = { 'apikey': '24115b5bd3d34ed28fc03a8c53eed18c',
'per_page': 3,
  # ...
  'phrase': 'election night',
  'state': 'MD'
}

endpoint = 'http://capitolwords.org/api/text.json'
response = requests.get(endpoint, params= query_params)

data = response.json
pprint.pprint(data)

Putting It All Together


# Codecademy Sample Solution

import requests

query_params = { 'apikey': '24115b5bd3d34ed28fc03a8c53eed18c',
    'phrase': 'fiscal cliff'
      }

endpoint = 'http://capitolwords.org/api/text.json'
response = requests.get(endpoint, params=query_params)

#request_url ?
request_url = response.url
print request_url

Make Your First JSON Request


# Codecademy Sample Solution

import requests
import pprint

query_params = { 'apikey': '24115b5bd3d34ed28fc03a8c53eed18c',
        'phrase': 'tax cuts'
      }

endpoint = 'http://capitolwords.org/api/text.json'

response = requests.get( endpoint, params=query_params)
data = response.json

pprint.pprint(data)

Thursday, January 24, 2013

Math Problems: A polynomial f(n) satisfies the equation...

Problem:

A polynomial f(n) satisfies the equation n^3 + 3n^2 + 3n + 1 = 2(f(n+1)) - f(n). Solve for f(10).

Answer: 777

Since the highest order is 3, we can assume that our function f(n) has the form
an^3 + bn^2 + cn + d

and 2(f(n+1)) has the form
2[a(n+1)^3 + b(n+1)^2 + c(n+1) + d]

After expanding, we can compare the coefficients on the left hand side with those on the right hand side:
a = 1
6a+b = 3, b = -3
6a+4b+c = 3, c = 9
2a + 2b + 2c + d = 1, d =-13

so f(n) = n^3 - 3n^2 + 9n - 13
Substitute a value of 10 for n will result in 777.



XML & JSON


# Codecademy sample solution

# What data format is shown below? Set answer
# equal to 'XML' for XML and 'JSON' for JSON.

# {
#   "Cartoon Foxes": {
#     {
#       "Name": "Fox Tall",
#       "Job": "Bein' tall"
#     },
#     {
#       "Name": "Fox Small",
#       "Job": "Bein' small"
#     }
#   }
# }

answer = 'JSON'

Authentication & API Keys


# Codecademy sample solution

# What's an API key?

# A: An alphanumeric string used to identify you to an API
# B: An OAuth token
# C: An All-Purpose Internet key
# D: The tool used to unlock an API gate

answer = 'A'

Requests


# Codecademy sample solution

from urllib2 import urlopen

# Add your code here!
website = urlopen('http://placekitten.com/')
kittens = website.read()

print kittens[559:1000]

REST Constraints & Requirements


# 1. HTTP is a protocol that connects clients and ______.
answer1 = 'servers'

# 2. The four HTTP methods are GET, POST, ___, and DELETE.
answer2 = 'PUT'

# 3. A ___ error means the server goofed up. (200, 300, 400, or 500)
answer3 = '500'

Anatomy of a Response


# Codecademy sample solution

################## Example response ##########################
# HTTP/1.1 200 OK
# Content-Type: text/xml; charset=UTF-8

# <?xml version="1.0" encoding="utf-8"?>
# <string xmlns="http://www.codecademy.com/">Accepted</string>
##############################################################

import requests
response = requests.get("http://placekitten.com/")

# print the header information from the response
print response.headers

HTTP Status Codes


# Codecademy sample solution

import requests

response = requests.get('http://placekitten.com/')

# Add your code below!
print response.status_code

Endpoints


# Codecademy sample solution

# What are the four commonly used HTTP methods ("verbs")?

# A: FIND, SEND, UPDATE, REMOVE
# B: CREATE, READ, UPDATE, DELETE
# C: GET, SEND, PUT, DELETE
# D: GET, POST, PUT, DELETE

answer = 'D'

Making a POST Request


# Codecademy sample solution

########## Example request #############
# POST /learn-http HTTP/1.1
# Host: www.codecademy.com
# Content-Type: text/html; charset=UTF-8
# Name=Eric&Age=26

import requests

body = {'Name': 'Eric', 'Age': '26'}

# Make the POST request here, passing body as the data:
response = requests.post('http://codecademy.com/learn-http/', data=body)

The Four Verbs


# Codecademy sample solution

import requests

# Make a GET request here and assign the result to kittens:
kittens = requests.get('http://placekitten.com/')

print kittens.text[559:1000]

Making a Request


# Codecademy sample solution

from urllib2 import urlopen

# Open http://placekitten.com/ for reading on line 4!
kittens = urlopen('http://placekitten.com/')

response = kittens.read()
body = response[559:1000]

# Add your 'print' statement here!
print(body)

Wednesday, January 23, 2013

Opening An Account


#Codecademy sample solution

class Account
    attr_reader :name
    attr_reader :balance

def initialize(name, balance=100)
@name = name
@balance = balance
end

private

def pin
@pin = 1234
end

def pin_error
return "Access denied: incorrect PIN."
end

public

def display_balance(pin_number)
if pin_number === pin
puts "Balance: $#{@balance}."
else
puts pin_error
end
end

def withdraw(pin_number, amount)
if pin_number === pin
@balance -= amount
puts "Withdrew #{amount}. New balance: $#{@balance}."
else
puts pin_error
end
end
end

#I wanna be a billionaire, so frekin' bad
checking_account = Account.new("Jim", 1_000_000_000)

Making a Withdrawal


#Codecademy sample solution

class Account
    attr_reader :name
    attr_reader :balance

def initialize(name, balance=100)
@name = name
@balance = balance
end

private

def pin
@pin = 1234
end

def pin_error
return "Access denied: incorrect PIN."
end

public

def display_balance(pin_number)
if pin_number === pin
puts "Balance: $#{@balance}."
else
puts pin_error
end
end

def withdraw(pin_number, amount)
if pin_number === pin
@balance -= amount
puts "Withdrew #{amount}. New balance: $#{@balance}."
else
puts pin_error
end
end
end

Displaying the Balance


#Codecademy sample solution

class Account
    attr_reader :name
    attr_reader :balance

def initialize(name, balance=100)
@name = name
@balance = balance
end

private

def pin
@pin = 1234
end

def pin_error
return "Access denied: incorrect PIN."
end

public

def display_balance(pin_number)
if pin_number === pin
puts "Balance: $#{@balance}."
else
puts pin_error
end
end
end

Private Affairs


#Codecademy sample solution

class Account
    attr_reader :name
    attr_reader :balance

def initialize(name, balance=100)
@name = name
@balance = balance
end

private

def pin
@pin = 1234
end

def pin_error
return "Access denied: incorrect PIN."
end
end

Codecademy: Creating the Account Class


#sample solution

class Account
    attr_reader :name
    attr_reader :balance
def initialize(name, balance=100)
@name = name
@balance = balance
end
end

Tuesday, January 22, 2013

Math Problems: Distinct Possible Sums


Question:
Given an array containing consecutive numbers from 1 to 16, how many sets of 3-number combinations exist where the sum of the three numbers is unique. The numbers in each set also have to be unique. For example, (1,1,16) is not allowed since 1 is repeated.

Answer: 40
Solved using the script below

console.log("*******************************");
var somearray = [];
for(var i=5; i<=50; i+=3){
//console.log(i);
somearray.push(i);
}
console.log(somearray);
var count=0;
var sumarray=[];
for(var i=0; i<somearray.length; i++){
for(var j=0; j<somearray.length; j++){
for(var k=0; k<somearray.length; k++){
if(i!==j && j!==k && k!==i){
var sum = somearray[i]+somearray[j]+somearray[k];
if(sumarray.indexOf(sum)<0){
sumarray.push(sum);
console.log(somearray[i]+" "+somearray[j]+" "+somearray[k]+" "+sum);
count++;
}
}
}
}
}
console.log("count is "+ count);

Math Problems: a+b+c

Question:
If the numbers a, b, and c are multiplied as abc, and the result is 100 and if (a^(log a / log 10)) * (b^(log b / log 10)) * (c^(log c / log 10)) >= 10000, what is the sum, a + bc?

Answer: 102

Solved using the script below which results in the only combination, 1, 1 and 100:


console.log("*******************************");
function log10(val){
return Math.log(val)/Math.LN10;
}

function aloga(x){
return Math.pow(x,log10(x));
}

var max = 200;
for(var i=1; i<=max; i++){
for(var j=1; j<=max; j++){
for(var k=1; k<=max; k++){
temp = aloga(i)*aloga(j)*aloga(k);
if(i*j*k===100 && temp>=10000){
console.log(i+" "+j+" "+k+" "+temp);
}
}
}
}

Codecademy Sample Solution: Mixin For the Win


module Languages
  FAVE = "Ruby"  # This is what you typed before, right? :D
end

class Master
  include Languages
  def initialize; end
  def victory
    puts FAVE
  end
end

total = Master.new
total.victory

Codecademy Sample Solution: Module Magic


# Create your module below!
module Languages
  FAVE = "Javascript"
end

Codecademy Sample Solution: Private Affairs


class Application
  attr_accessor :status
  def initialize; end
  # Add your method here!
  public
  def print_status
  puts "All systems go!"
  end
 
  private
  def password
    return 12345
  end
end

Codecademy Sample Solution: A Matter of Public Knowledge


class Application
  attr_accessor :status
  def initialize; end
  # Add your method here!
  public
  def print_status
  puts "All systems go!"
  end
end

Codecademy Sample Solution: Imitating Multiple Inheritance


# Create your module here!
module MartialArts
def swordsman
puts "I'm a swordsman."
end
end

class Ninja
  include MartialArts
  def initialize(clan)
    @clan = clan
  end
end

class Samurai
  include MartialArts
  def initialize(shogun)
    @shogun = shogun
  end
end

#test
Leo = Ninja.new("Tutle")
Leo.swordsman

Himura = Samurai.new("Hogan")
Himura.swordsman

Monday, January 21, 2013

Codecademy Sample Solution: Feeling Included


class Angle
  include Math
  attr_accessor :radians
 
  def initialize(radians)
    @radians = radians
  end
 
  def cosine
    cos(@radians)
  end
end

acute = Angle.new(1)
acute.cosine

Codecademy Sample Solution: A Few Requirements


require 'date'

puts Date.today

Codecademy Sample Solution: Resolve to Keep Learning!


# Write your code below!
puts Math::PI

Codecademy Sample Solution: Module Syntax


module MyLibrary
FAVE_BOOK = "Bible"
end

Fibonacci Sequence Generator

Type in the maximum cut-off (For example, say you want all Fibonacci numbers less than 10, then type 10):
Maximum Cut-off
Note: Iterations are limited to 1000. This limits the values you can use for the maximum cut-off.

Generate

Math Problems: Digit Sum

Question:
How many numbers between 1000 and 9999 satisfy the condition that the thousands digit is equal to the sum of the hundreds, tens and ones digit?

Answer: 219

Solution: Solved using the script below


console.log("*************************************")
var count=0;
for(var i=0; i<10000; i++){
if(i>=1000){
var temp = i.toString();
tho = parseInt(temp[0]);
hun = parseInt(temp[1]);
ten = parseInt(temp[2]);
one = parseInt(temp[3]);
if(tho === hun+ten+one){
console.log(tho+" "+hun+" "+ten+" "+one);
count++;
}
}
}
console.log("count is "+count);


Sunday, January 20, 2013

Prime Number Array Generator

Type in the maximum cut-off (For example, say you want all Prime numbers less than 1000, then type 1000):
Maximum Cut-off
Note: Iterations are limited to 1 million for now to avoid extremely long computation. This limits the values you can use for the maximum cut-off.

Generate

Sum of Prime Numbers Array Generator

Type in the maximum cut-off (For example, say you want all Prime number sums less than 1000, then type 1000):
Maximum Cut-off
Note: Iterations are limited to 1 million for now to avoid extremely long computation. This limits the values you can use for the maximum cut-off.

Generate

Array of Sum of Prime Numbers Less Than 1000

Below is an array containing the sum of consecutive prime numbers that's less than 1000. For example, the first entry is simply 2, the second entry, 5, is the sum of 2 and 3, the third entry, 10, is the sum of 2, 3 and 5, and so on and so forth.


[ 2,
  5,
  10,
  17,
  28,
  41,
  58,
  77,
  100,
  129,
  160,
  197,
  238,
  281,
  328,
  381,
  440,
  501,
  568,
  639,
  712,
  791,
  874,
  963 ]

Codecademy Sample Solution: attr_accessor


class Person
  attr_reader :name
  attr_accessor :job
 
  def initialize(name, job)
    @name = name
    @job = job
  end
end

client = Person.new("Jim", "programmer")
puts "#{client.name} is a #{client.job}"
client.job = "dentist"
puts "#{client.name} is a #{client.job}"

Codecademy Sample Solution: attr_reader, attr_writer


class Person
  attr_reader :name
  attr_reader :job
  attr_writer :job
  def initialize(name, job)
    @name = name
    @job = job
  end
end

client = Person.new("Jim", "programmer")
puts "#{client.name} is a #{client.job}"
client.job = "dentist"
puts "#{client.name} is a #{client.job}"

Codecademy Sample Solution: Private! Keep Out!


class Dog
def initialize(name, breed)
@name = name
@breed = breed
end

public
def bark
puts "Woof!"
end

private
def id
@id_number = 12345
end
end

Codecademy Sample Solution: Going Public


class Dog
def initialize(name, breed)
@name = name
@breed = breed
end

public
def bark
puts "Woof!"
end
end

#test
contestant1 = Dog.new("Snoopy", "Beagle")
contestant1.bark

Codecademy Sample Solution: Quick Review: Building a Class


class Dog
def initialize(name, breed)
@name = name
@breed = breed
end
end

Codecademy Sample Solution: Instantiation Nation


class Computer
@@users = {}

def Computer.get_users
return @@users
end

def initialize(username, password)
@username = username
@password = password
@files = {}
@@users[username] = password
end

def create(filename)
@filename = filename
@time = Time.now
@files[filename] = @time
puts "A new file was created: #{@filename} #{@username} #{@time}"
end
end

my_computer = Computer.new("Jim", test)

Codecademy Sample Solution: Who're the Users?


class Computer
@@users = {}

def Computer.get_users
return @@users
end

def initialize(username, password)
@username = username
@password = password
@files = {}
@@users[username] = password
end

def create(filename)
@filename = filename
@time = Time.now
@files[filename] = @time
puts "A new file was created: #{@filename} #{@username} #{@time}"
end
end

Codecademy Sample Solution: Getting More Creative


class Computer
@@users = {}

def initialize(username, password)
@username = username
@password = password
@files = {}
@@users[username] = password
end

def create(filename)
@filename = filename
@time = Time.now
@files[filename] = @time
puts "A new file was created: #{@filename} #{@username} #{@time}"
end
end

Codecademy Sample Solution: Have A Little Class


class Computer
@@users = {}

def initialize(username, password)
@username = username
@password = password
@files = {}
@@users[username] = password
end
end

Codecademy Sample Solution: Fancify Your Initialize Method


class Computer
def initialize(username, password)
@username = username
@password = password
@files = {}
end
end

Codecademy Sample Solution: Create Your Class


class Computer
def initialize
end
end

Saturday, January 19, 2013

Codecademy Sample Solution: Up, Up and Away!


class Message

@@messages_sent = 0

def initialize(from, to)
@from = from
@to = to
@@messages_sent += 1
end
end

class Email < Message
def initialize(from, to)
super
end
end

Codecademy Sample Solution: Inheriting a Fortune


class Message

@@messages_sent = 0

def initialize(from, to)
@from = from
@to = to
@@messages_sent += 1
end
end

class Email < Message
def initialize(subject)
@subject = subject
end
end

Codecademy Sample Solution: Forge an Object in the Fires of Mount Ruby


class Message

@@messages_sent = 0

def initialize(from, to)
@from = from
@to = to
@@messages_sent += 1
end
end

my_message = Message.new("Anne", "Jim")

Codecademy Sample Solution: Getting Classier


class Message

@@messages_sent = 0

def initialize(from, to)
@from = from
@to = to
@@messages_sent += 1
end
end

Codecademy Sample Solution: Class Basics


class Message
def initialize(from, to)
@from = from
@to = to
end
end

Codecademy Sample Solution: When Good isn't Good Enough


class Creature
  def initialize(name)
    @name = name
  end
 
  def fight
    return "Punch to the chops!"
  end
end

# Add your code below!

class Dragon < Creature
  def fight
    puts "Instead of breathing fire..."
    super
  end
end

Codecademy Sample Solution: Override!


class Creature
  def initialize(name)
    @name = name
  end
 
  def fight
    return "Punch to the chops!"
  end
end

# Add your code below!

class Dragon < Creature
  def fight
    return "Breathes fire!"
  end
end

Codecademy Sample Solution: Inheritance Syntax


class Application
  def initialize(name)
    @name = name
  end
end

# Add your code below!

class MyApp < Application
end

Codecademy Sample Solution: Twice the @, Twice as Classy


class Person
  # Set your class variable to 0 on line 3
  @@people_count = 0
 
  def initialize(name)
    @name = name
    # Increment your class variable on line 8
    @@people_count += 1
  end
 
  def self.number_of_instances
    # Return your class variable on line 13
    return @@people_count
  end
end

matz = Person.new("Yukihiro")
dhh = Person.new("David")

puts "Number of Person instances: #{Person.number_of_instances}"

Codecademy Sample Solution: For Instance...


class Person
  def initialize(name, age, profession)
    @name = name
    @age = age
    @profession = profession
  end
end

Codecademy Sample Solution: Naming Your Variables


class MyClass
  my_variable = "Hello!"
end

puts $my_variable

Thursday, January 17, 2013

Math Problems: How Many Three Digit Numbers?

Question:

How many three digit numbers are there such that the hundreds digit is less than or equal to the tens digit and the ones digit is less than or equal to the tens digit?

Answer: 330

Solved using the script below:


console.log("***************************************");
function threeDigitNum(a,b,c){
return a*100 + b*10 + c*1;
}

var count=0;
for(var i=0; i<=9; i++){
for(var j=0; j<=9; j++){
for(var k=0; k<=9; k++){
var temp = threeDigitNum(i,j,k);
if(i<=j && k<=j && temp>=100){
console.log("i: "+i+" j: "+j+" k: "+k+" num:"+temp);
count++;
}
}
}
}

console.log("count is "+count);

Codecademy Sample Solution: Passing Your Lambda to a Method


crew = {
  captain: "Picard",
  first_officer: "Riker",
  lt_cdr: "Data",
  lt: "Worf",
  ensign: "Ro",
  counselor: "Troi",
  chief_engineer: "LaForge",
  doctor: "Crusher"
}
# Add your code below!

first_half = lambda { |key, value| value < "M" }

a_to_m = crew.select(&first_half)

Codecademy Sample Solution: Creating a Lambda


crew = {
  captain: "Picard",
  first_officer: "Riker",
  lt_cdr: "Data",
  lt: "Worf",
  ensign: "Ro",
  counselor: "Troi",
  chief_engineer: "LaForge",
  doctor: "Crusher"
}
# Add your code below!

first_half = lambda { |key, value| value < "M" }

Codecademy Sample Solution: Passing Your Proc to a Method


ages = [23, 101, 7, 104, 11, 94, 100, 121, 101, 70, 44]

# Add your code below!

under_100 = Proc.new {|num| num < 100}

youngsters = ages.select(&under_100)

Codecademy Sample Solution: Creating a Proc


ages = [23, 101, 7, 104, 11, 94, 100, 121, 101, 70, 44]

# Add your code below!

under_100 = Proc.new {|num| num < 100}

Codecademy Sample Solution: Been Around the Block a Few Times


odds_n_ends = [:weezard, 42, "Trady Blix", 3, true, 19, 12.345]

ints = odds_n_ends.select{ |element| element.is_a? Integer }

Codecademy Sample Solution: Now You Try!


my_array = ["raindrops", :kettles, "whiskers", :mittens, :packages]

# Add your code below!

symbol_filter = lambda { |element| element.is_a? Symbol }

symbols = my_array.select(&symbol_filter)

Codecademy Sample Solution: Lambda Syntax


strings = ["leonardo", "donatello", "raphael", "michaelangelo"]
# Write your code below this line!

symbolize = lambda { |element| element.to_sym }

# Write your code above this line!
symbols = strings.collect(&symbolize)

Codecademy Sample Solution: Symbols, Meet Procs


numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

strings_array = numbers_array.collect(&:to_s)

Codecademy Sample Solution: Call Me Maybe


hi = Proc.new { puts "Hello!"}
hi.call

Codecademy Sample Solution: Create Your Own!


def greeter
yield
end

phrase = Proc.new { puts "Hello there!"}

greeter(&phrase)

Codecademy Sample Solution: Why Procs?


# Here at the amusement park, you have to be four feet tall
# or taller to ride the roller coaster. Let's use .select on
# each group to get only the ones four feet tall or taller.

over_4_feet = Proc.new { |height| height >= 4 }

group_1 = [4.1, 5.5, 3.2, 3.3, 6.1, 3.9, 4.7]
group_2 = [7.0, 3.8, 6.2, 6.1, 4.4, 4.9, 3.0]
group_3 = [5.5, 5.1, 3.9, 4.3, 4.9, 3.2, 3.2]

print can_ride_1 = group_1.select(&over_4_feet)
puts
print can_ride_2 = group_2.select(&over_4_feet)
puts
print can_ride_3 = group_3.select(&over_4_feet)

Codecademy Sample Solution: Proc Syntax


floats = [1.2, 3.45, 0.91, 7.727, 11.42, 482.911]
# Write your code below this line!

round_down = Proc.new {|num| num.floor }

# Write your code above this line!
ints = floats.collect(&round_down)

Codecademy Sample Solution: Try It Yourself


def double(param)
yield param
end

double(5) {|param| puts param * 2}

Codecademy Sample Solution: Yielding With Parameters


def yield_name(name)
  puts "In the method! Let's yield."
  yield name
  puts "Block complete! Back in the method."
end

yield_name("Eric") { |name| puts "My name is #{name}." }

# Now call the method with your name!

yield_name("Jim") { |name| puts "My name is #{name}."}

Codecademy Sample Solution: Collect 'Em All

fibs = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

# Add your code below!
doubled_fibs = fibs.collect { |num| num * 2 }

Wednesday, January 16, 2013

Codecademy Sample Solution: You Know This!


# Write your code below!
5.times { puts "I'm a block!" }

Codecademy Sample Solution: Final Push


$VERBOSE = nil    # We'll explain this at the end of the lesson.
require 'prime'   # This is a module. We'll cover these soon!

def first_n_primes(n)

  return "n must be an integer." unless n.is_a? Integer

  return "n must be greater than 0." if n <= 0
 
  prime_array ||= []
 
  prime = Prime.new
  n.times { prime_array << prime.next }
  prime_array
end

first_n_primes(10)

Codecademy Sample Solution: The Rubyist's Loop


$VERBOSE = nil    # We'll explain this at the end of the lesson.
require 'prime'   # This is a module. We'll cover these soon!

def first_n_primes(n)

  return "n must be an integer." unless n.is_a? Integer

  return "n must be greater than 0." if n <= 0
 
  prime_array ||= []
 
  prime = Prime.new
  n.times { prime_array.push(prime.next) }
  prime_array
end

first_n_primes(10)

Codecademy Sample Solution: Less is More


$VERBOSE = nil    # We'll explain this at the end of the lesson.
require 'prime'   # This is a module. We'll cover these soon!

def first_n_primes(n)

  return "n must be an integer." unless n.is_a? Integer

  return "n must be greater than 0." if n <= 0
 
  prime_array ||= []
 
  prime = Prime.new
  for num in (1..n)
    prime_array.push(prime.next)
  end
  prime_array
end

first_n_primes(10)

Codecademy Sample Solution: Omit Needless Words


$VERBOSE = nil    # We'll explain this at the end of the lesson.
require 'prime'   # This is a module. We'll cover these soon!

def first_n_primes(n)

  return "n must be an integer." unless n.is_a? Integer

  return "n must be greater than 0." if n <= 0
 
  prime_array ||= []
 
  prime = Prime.new
  for num in (1..n)
    prime_array.push(prime.next)
  end
  return prime_array
end

first_n_primes(10)

Codecademy Sample Solution: To Be or Not to Be


$VERBOSE = nil    # We'll explain this at the end of the lesson.
require 'prime'   # This is a module. We'll cover these soon!

def first_n_primes(n)

  unless n.is_a? Integer
    return "n must be an integer."
  end

  if n <= 0
    return "n must be greater than 0."
  end
 
  prime_array ||= []
 
  prime = Prime.new
  for num in (1..n)
    prime_array.push(prime.next)
  end
  return prime_array
end

first_n_primes(10)

Brahmagupta's Formula for Solving a Quadrilateral's Area

Type in the length of the sides of a quadrilateral:
Side A meters
Side B meters
Side C meters
Side D meters

Compute

Heron's Formula for Solving a Triangle's Area

Type in the length of the sides of a triangle:
Side A meters
Side B meters
Side C meters

Compute

Tuesday, January 15, 2013

Brahmagupta's Formula For Quadrilateral Area


Question: What is the area of a quadrilateral with sides equal to 18, 22, 39, and 41 respectively?

Answer: 798

console.log("********************************");
function Brahmagupta(a,b,c,d){
var perimeter=a+b+c+d;
var s = perimeter/2;
return Math.sqrt((s-a)*(s-b)*(s-c)*(s-d));
}
console.log(Brahmagupta(18,22,39,41));

Heron's Triangle Area Formula Javascript Implementation


Question: Given a triangle with sides 13, 14 and 15, what is it's area?

Answer: 84

Solved using the script below:

console.log("********************************");
function Herons(a,b,c){
var perimeter=a+b+c;
var s = perimeter/2;
return Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
console.log(Herons(13,14,15));

Math Problems: x^2+2

Question: If a function is f(x) = x^2+2, what is the product of f(x1)*f(x2)*f(x3)*f(x4)? The values of x1 to x4 are as follows.


x1 = 0.27702;
x2 = -0.30596;
x3 = -1.96758;
x4 = 5.99652;

Answer: 969

Solved using the script below:


console.log("********************************");
function func(x){
return Math.pow(x,2)+2;
}
X1 = 0.27702;
X2 = -0.30596;
X3 = -1.96758;
X4 = 5.99652;

product=func(X1)*func(X2)*func(X3)*func(X4);

console.log(product);

Math Problems x^4+64

Question: What is the equivalent fraction of the expression below?

(8^4+64)(16^4+64)(24^4+64)(32^4+64)(40^4+64)(48^4+64)(56^4+64)(64^4+64)
----------------------------------------------------------------------------------------
(4^4+64)(12^4+64)(20^4+64)(28^4+64)(36^4+64)(44^4+64)(52^4+64)(60^4+64)
(84+64)(164+64)(244+64)(324+64)(404+64)(484+64)(564+64)(644+64)(44+64)(124+64)(204+64)(284+64)(364+64)(444+64)(524+64)(604+64)
(84+64)(164+64)(244+64)(324+64)(404+64)(484+64)(564+64)(644+64)(44+64)(124+64)(204+64)(284+64)(364+64)(444+64)(524+64)(604+64)

Answer: 545

Solved using the script below:


console.log("********************************");
function func(x){
return Math.pow(x,4)+64;
}
var numproduct=1;
for(var i=8; i<=64; i+=8){
var temp = func(i);
console.log(i+" "+temp);
numproduct *= temp;
}

var denproduct=1;
for(var i=4; i<=60; i+=8){
var temp = func(i);
console.log(i+" "+temp);
denproduct *= temp;
}

console.log(numproduct/denproduct);

This is an example of scrolling text using Javascript.

Popular Posts