├── .gitignore
├── .jshintrc
├── README.md
├── future-exercises.md
└── problems
├── prob01
├── prob1.js
├── prob1.py
├── prob1.rb
└── prob1es6.js
├── prob02
├── prob2.coffee
├── prob2.js
├── prob2.py
├── prob2.rb
└── prob2es6.js
├── prob03
├── prob3.js
├── prob3.py
├── prob3.rb
└── prob3es6.js
├── prob04
├── prob4.js
├── prob4.py
├── prob4.rb
└── prob4es6.js
├── prob05
├── prob5.js
├── prob5.py
├── prob5.rb
└── prob5es6.js
├── prob06
├── prob6.js
├── prob6.py
├── prob6.rb
└── prob6es6.js
├── prob07
├── js
│ ├── js
│ │ └── main.js
│ └── test
│ │ ├── index.html
│ │ └── test.js
├── prob7.py
└── prob7.rb
├── prob08
├── js
│ ├── js
│ │ └── main.js
│ └── test
│ │ ├── index.html
│ │ └── test.js
├── prob8.py
├── prob8.rb
├── prob8_test.py
└── prob8_test.rb
├── prob09
├── prob9.coffee
├── prob9.js
├── prob9.py
├── prob9.rb
└── prob9es6.js
├── prob10
├── prob10.js
├── prob10.py
└── prob10.rb
├── prob11
├── prob11.js
├── prob11.py
└── prob11.rb
├── prob12
├── js
│ ├── index.html
│ ├── main.js
│ └── test.js
├── prob12.rb
├── prob12a.py
└── prob12b.py
├── prob13
├── prob13.js
└── prob13.py
├── prob14
├── prob14.js
└── prob14es6.js
├── prob15
├── prob15.js
└── prob15es6.js
├── prob16
├── prob16.js
└── prob16es6.js
├── prob17
├── prob17.html
└── prob17.js
├── prob18
├── prob18.html
└── prob18.js
├── prob19
├── prob19.html
├── prob19.js
├── prob19.py
└── prob19.rb
├── prob20
└── prob20.py
├── prob21
├── prob21.html
├── prob21.js
├── prob21.py
└── prob21.rb
├── prob22
├── prob22.html
├── prob22.js
├── prob22.py
└── prob22.rb
├── prob23
├── prob23.html
├── prob23.js
└── prob23.rb
├── prob24
├── prob24.html
├── prob24.js
└── prob24.rb
├── prob25
├── prob25.html
├── prob25.js
└── prob25.py
├── prob26
├── prob26.html
└── prob26.js
├── prob27
├── prob27.html
└── prob27.js
├── prob28
├── prob28.py
├── prob28.rb
└── prob28b.rb
├── prob29
└── prob29.rb
├── prob30
├── prob30.css
├── prob30.html
└── prob30.js
├── prob31
├── prob31.css
├── prob31.html
└── prob31.js
├── prob32
├── prob32.css
├── prob32.html
└── prob32.js
├── prob33
├── prob33.css
├── prob33.html
├── prob33.js
└── prob33.md
├── prob34
└── prob34.py
├── prob35
├── prob35.js
├── prob35.py
└── prob35.rb
├── prob36
├── prob36.html
├── prob36.js
└── prob36.rb
├── prob37
└── prob37.js
├── prob38
├── prob38.js
└── prob38.rb
├── prob39
├── index.html
├── main.css
└── main.js
├── prob40
└── main.js
├── prob41
└── main.js
├── prob42
└── boom.js
├── prob43
├── longest_palindrome.js
└── longest_palindrome_brute.js
├── prob44
├── byte-string.js
├── my-solution-byte-string-spec.js
├── my-solution-byte-string.js
└── test-byte-string.js
├── prob45
├── csv_parse.js
└── test-csv-parse.js
├── prob46
└── vowels.js
├── prob47
├── main.js
└── util.js
├── prob48
├── index.html
├── main.js
└── test.js
├── prob49
├── index.html
├── main.js
└── test.js
├── prob50
├── index.html
├── main.js
└── test.js
├── prob51
└── main.js
├── prob52
├── index.html
├── main.js
└── test.js
├── prob53
├── index.html
├── main.js
└── test.js
├── prob54
├── index.html
├── main.js
└── test.js
├── prob55
├── index.html
├── main.js
└── test.js
└── prob56
├── index.html
├── main.js
└── test.js
/.gitignore:
--------------------------------------------------------------------------------
1 | *.DS_Store
2 | *.pyc
3 | node_modules
4 |
--------------------------------------------------------------------------------
/.jshintrc:
--------------------------------------------------------------------------------
1 |
2 | {
3 | "globals": {
4 | "esnext": true,
5 | "jasmine": false,
6 | "spyOn": false,
7 | "it": false,
8 | "console": false,
9 | "describe": false,
10 | "expect": false,
11 | "beforeEach": false,
12 | "afterEach": false,
13 | "waits": false,
14 | "waitsFor": false,
15 | "runs": false,
16 | "$": false,
17 | "confirm": false
18 | },
19 | "esnext": true,
20 | "node" : true,
21 | "browser" : true,
22 | "boss" : false,
23 | "curly": false,
24 | "debug": false,
25 | "devel": false,
26 | "eqeqeq": true,
27 | "evil": true,
28 | "forin": false,
29 | "immed": true,
30 | "laxbreak": false,
31 | "newcap": true,
32 | "noarg": true,
33 | "noempty": false,
34 | "nonew": false,
35 | "nomen": false,
36 | "onevar": true,
37 | "plusplus": false,
38 | "regexp": false,
39 | "undef": true,
40 | "sub": true,
41 | "strict": false,
42 | "white": true,
43 | "unused": false
44 | }
45 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Problems
2 |
3 | *Solved with brute force*
4 |
5 | 1. **Basic Stats**: Generate two random integers and print their mean, variance, and standard deviation.
6 | 1. **Basic Stats (take 2)**: Calculate the mean, variance, and standard deviation for an array containing 10 random integers.
7 | 1. **Largest and Smallest**: Generate twenty random integers from 0 to 100 and output the largest and smallest integers.
8 | 1. **Even Integer Output**: Generate a single random number, from 0 to 100, then output all the even integers from 0 to the random number.
9 | 1. **Odd Integer Output**: Generate a single random number, from 0 to 100. If the number is greater than 40 then output all the odd integers from 40 to the random number. If the number is less than 40, output all the odd integers from 0 to 40.
10 | 1. **Odd Integer Output** (take 2): Generate a single random number, from 0 to 100. If the number is greater than 40 then output all the odd integers from that number down to 40. If the number is less than 40, output all the odd integers from that number down to 0.
11 | 1. **Discount Percentage**: Write a function that takes a dollar amount and a discount percentage and returns the total discount amount. Return a warning if the discount amount is greater than 100 or less that 0 percent. Test the results.
12 | 1. **Class it up**: Wrap a class around the last function. Instantiate the class and call the function. Then write tests.
13 | 1. **Output Ascending**: Generate n random integers from 0 to 100, then output them in ascending order.
14 | 1. **Sum Digits**: Generate a random number from 1000 to 9999 and output the sum of its digits. For example, if the number is 1049, then the output should be 14.
15 | 1. **Sum Digits w/drop**: Generate a random number from 1000 to 9999 and output the sum of its digits, repeatedly, dropping the left-most digit after each iteration, until there is only one digit only. For example, if the number is 1049, then the output should be 14, 13, 13, 9.
16 | 1. **Least Common Denominator**: Generate two random integers from 0 to 100 and output the smallest number such that each shares a least common denominator (aside for 1). For example, 18 and 6 should return 6, while 9 and 4 should return False. Return False if the two numbers are equal.
17 | 1. **Least Common Multiple**: Write a function that takes two random integers as arguments and returns the least common multiple.
18 | 1. **Power**: Write a program that calculates and shows the value of (x to the nth power). Let both integers fall within the range of 2 through 20.
19 | 1. **Simple Triangle**: Write a function that takes a single number as an input and returns that many lines. On the first line there is one '#' character. On the second there are two. And so on. This will create a nice triangle.
20 | 1. **Random String Test**: Write a function that takes two random 10-character strings as arguments, which returns True when the first string starts with the first two characters in the second string - and False otherwise.
21 | 1. Write a function that takes a paragraph as an argument and returns an array that contains each string as an element.
22 | 1. Create a simple webpage that includes three tags, an `
`, `
` and `
`, then using jQuery, create an alert that outputs the tag name when you click on the tag.
23 | 1. Write a function that takes an object/hash/dictionary of people (keys) and their subsequent ages as its argument, and then it returns the name of the oldest living person.
24 | 1. Write two functions. Both take a base and an exponent as arguments and return the value of base^exponent. Use recursion in the first function and a loop in the second. Benchmark the results.
25 | 1. **Reverse**: Write a function that takes a string as an argument and returns the string in reversed order. Test if the string is the same reversed (Palindrome).
26 | 1. **Factorial**: Write a function that takes a random number as an argument and then returns the factorial of that given number.
27 | 1. **Longest Word**: Write a function that takes a string and returns the longest word in the string.
28 | 1. **Longest Word 2**: Refactor the "Longest Word" function so that it ignores punctuation.
29 | 1. **Time Difference**: Write a function that takes two times in hours and minutes and returns the difference.
30 | 1. **Time Convert**: Write a function that takes an integer then returns the number in hours and minutes. For example, 63 should return 1:3.
31 | 1. Using JavaScript, create a function that handles errors. The function takes two integers as inputs and returns the result of dividing them. If the denominator is 0, throw an error.
32 | 1. **Spiral**: Write a function called "spiral" that takes an NxM array as input and returns a "spiral" path through the array, starting in the upper-left corner and moving clockwise. For example: [[1,2,3],[8,9,4],[7,6,5]] => [1,2,3,4,5,6,7,8,9]
33 | 1. **Password Generator**: Write a function that takes an integer as an input and returns a random password - with upper and lowercase letters, integers, and characters - the length of the integer.
34 | 1. Using jQuery and CSS, create new .js and .css files (prob30.css and prob30.js, respectively) so that when a user clicks on a button, the background color of the page will change. Use the HTML code in the corresponding folder. You do not have to edit the file.
35 | 1. **Mad Libs**: Using HTML, CSS, and jQuery, create a mad libs game. Use an HTML form to take user input. Display the results however you'd like. Get creative.
36 | 1. Create a simple to-do list using jQuery. Make sure the user can remove the items.
37 | 1. Create an app that pulls in your Github repos using AJAX. PUSH it to Heroku (using static files). Document the PUSH process. [http://git-ajax.herokuapp.com/](http://git-ajax.herokuapp.com/)
38 | 1. Write a function that takes a single string as the input then return the number of vowels the string contains. Do not count "y" as a vowel.
39 | 1. **Xs and 0s**: Create a function that takes a string of "x"s and "o"s as inputs. Return `True` if the number of "x"s and "o"s is even - and `False` otherwise.
40 | 1. Write a function that takes an array of integers and returns the number of users in it. Then refactor this to use a helper function to first test whether an integer is zero or not that's called from the original function.
41 | 1. Write a function that takes the following arguments-
42 | - `% The Book of Programming`
43 | - `%% The Two Aspects`
44 | - `Below the surface of the machine, the program moves. Without effort, it expands and contracts. In great harmony, electrons scatter and regroup. The forms on the monitor are but ripples on the water. The essence stays invisibly below.`
45 |
46 | And then checks the type (HTML tag) of the argument (H1, HX, or p). H1 has one "%", HX has two "%", and a p has none. Return each argument without the "&" characters as well as the type.
47 | 1. Build a function, `splitParagraph()`, which, takes a paragraph string as an input, and returns an array of paragraph fragments. (do not use any punctuation)
48 | 1. **Guessing Game**: Create a basic website that asks the user to input an integer from 1 to 100. When the user inputs a number, it should tell the user if the number they entered is too high, too low, or the exact number. When the game is over - e.g., when the user guesses correctly - display a "Start Over" button allowing the user to play again! Also, add a "Give Up" button, which displays the number and starts the game over. You should only have three files - *index.html*, *main.js*, and *main.css*. Use either jQuery or Angular for interacting with the DOM.
49 | 1. **One Missing**: Write a function that takes an array of integers between 1 and 10, with one missing integer, as an argument and returns the missing integer. Test this with Mocha and Chai.
50 | 1. **Find Odd Occurring Element**: Given an integer array, one element occurs odd number of times and all others have even occurrences. Find the element with odd occurrences.
51 | 1. **Find Next Higher Number With Same Digits**: Write a function that takes an integer and returns the next higher number that uses only the digits in that number. For example - 1345 => 1354. Hint: Write tests first!
52 | 1. **Longest Palindrome**: Write a function that takes a string as an argument and finds the longest palindrome, including whitespace. So, given the string "I am a dazzled racecar driver", the function should return "d racecar d".
53 | 1. **Byte String**: Write a function that takes an integer as an argument and converts it to a string that represents a rounded size in bytes. Examples:
54 | - 10221 => "9.98 KB"
55 | - 1022932324 => "975.54 MB"
56 | 1. **CSV Parse**: Write a function that takes a string as an argument, where all values are either and integer or a string, and then return an array of the parsed input string. Examples:
57 | - '3,7,9,1,25' => [ 3, 7, 9, 1, 25 ]
58 | - '1, "one", 2, "two", 3, "three"' => [1, "one", 2, "two", 3, "three"]
59 | 1. Create a function that takes a word as an argument and returns true if and only if all of the vowels in the word are the same.
60 | - myFn('oligopoly') => false
61 | - myFn('zoom') => true
62 | 1. **Flatten Array/Custom Callback**: Create a function that takes a nested array and a callback as arguments and returns a single, flattened array. Make sure to handle errors as well. Use a module to handle the work, making sure to export the function. Then call the function in a different file, passing in the arguments (array, callback).
63 | 1. **Intersection**: Write a function called `intersection` that takes two arrays as arguments and returns an array of the items that are in both input arrays. For example => intersection([1,2,3], [1,3,5]) should return [1,3]. Write tests!
64 | 1. **Count It**: Count the letters in a string.
65 | - Input: A string - like `'Hello World'`
66 | - Output: Letters and how often they show up. - `d:1 e:1 h:1 l:3 o:2 r:1 w:1`
67 | - Special: Convert all to lowercase. Ignore whitespace and anything not a-z
68 | - Challenge input: 'The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.'
69 | 1. **Ramp Numbers** A ramp number is a number whose digits from left to right either only rise or stay the same. 1234 is a ramp number as is 1124. 1032 is not.
70 | - Input: A positive integer, `n`.
71 | - Output: `true` if the input is a ramp number, `false` if it is not
72 | 1. **Palindrome**: Write a program to test if a string is palindromic. A Palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Allowances may be made for adjustments to capital letters, punctuation, and word dividers.
73 | 1. **Combine and Sort**: Write a non-destructive function that takes two arrays and returns a new array with all items in alphabetical order.
74 | - Input: Two arrays, `['cat', 'dog', 'fish', 'zebra']`, `['lion', 'aardvark', 'gorilla']`
75 | - Output: A new array with all items in alphabetical order, `['aardvark', 'cat', 'dog', 'fish', 'gorilla', 'lion', 'zebra']`
76 | 1. **Product of Five**: Write a function called `productOfFive` that takes an integer and returns the product of the 5 adjacent numbers whose product is the largest.
77 | - Input: `111333321`
78 | - Output: `162`
79 | 1. **Rotate Matrix**: Write a function named `rotateMatrix()` that takes a rectangular array of numbers (a matrix) and returns the matrix rotated 90 degrees to the right.
80 | - Input: `[ [29, 62, 8], [12, 60, 31], [99, 79, 12] ];`
81 | - Output: `[ [99, 12, 29], [79, 60, 62], [12, 31, 8] ];`
82 | 1. **Weird Words**: Write a function `weirdWords()` that takes a string and changes every letter to the next letter in the alphabet and then returns the result. Note: spaces and special characters should remain the same. Capital letters should remain capitalized.
83 | - Input: `What is your name?`
84 | - Output: `Xibu jt zpvs obnf?`
85 | 1. **Two Sum**: Write a function that takes an array of integers and a target integer. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in an array like so: [index1, index2].
86 | - input: `[1, 2, 3, 4, 5, 6, 7], 13`
87 | - output: `[5, 6]`
88 |
--------------------------------------------------------------------------------
/future-exercises.md:
--------------------------------------------------------------------------------
1 | 1. A function cal1ed "union" that takes two arrays as arguments and returns an array of items from both arrays. For example, union([1,2,3], [4,5,6]) should return [1,2,3,4,5,6].
2 | 1. A function called "zip" that takes two arrays as arguments and returns an array of items from both arrays combined in an alternating manner. For example, zip([1,2,3], [4,5,6]) should return [1,4,2,5,3,6].
3 | 1. https://github.com/mjhea0/recursion-joy
4 |
--------------------------------------------------------------------------------
/problems/prob01/prob1.js:
--------------------------------------------------------------------------------
1 | var num1 = Math.floor((Math.random() * (100)));
2 | var num2 = Math.floor((Math.random() * (100)));
3 |
4 | var avg = mean(num1, num2);
5 | var variance = variance(num1, num2, avg);
6 | var stdDev = stdDev(variance);
7 |
8 | console.log('Numbers: ' + num1 + ', ' + num2);
9 | console.log('Mean: ' + avg);
10 | console.log('Variance: ' + variance);
11 | console.log('Standard Deviation: ' + stdDev);
12 |
13 | function mean(num1, num2) {
14 | return (num1 + num2) / 2;
15 | }
16 |
17 | function variance(num1, num2 , avg) {
18 | return Math.pow((num1 - avg), 2) + Math.pow((num2 - avg), 2);
19 | }
20 |
21 | function stdDev(variance) {
22 | return Math.sqrt(variance);
23 | }
24 |
--------------------------------------------------------------------------------
/problems/prob01/prob1.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 | from math import sqrt
3 |
4 |
5 | def variance(n1, n2, average):
6 | return (n1 - average)**2 + (n2 - average)**2
7 |
8 |
9 | def std_dev(variance):
10 | std = sqrt(variance)
11 | return std
12 |
13 | num1 = randrange(100)
14 | num2 = randrange(100)
15 | print("The numbers are {0} and {1}".format(num1, num2))
16 |
17 |
18 | avg = (num1 + num2) / 2
19 | print("The average is " + str(avg))
20 |
21 | var = variance(num1, num2, avg)
22 | print("The variance is: " + str(var))
23 |
24 | print("The standard dev is " + str(round((std_dev(var)), 2)))
25 |
--------------------------------------------------------------------------------
/problems/prob01/prob1.rb:
--------------------------------------------------------------------------------
1 | def variance(n1,n2,avg)
2 | num1 = (n1-avg)**2
3 | num2 = (n2-avg)**2
4 | return num1 + num2
5 | end
6 |
7 | def std_dev(variance)
8 | std = Math.sqrt(variance)
9 | return std
10 | end
11 |
12 | num1 = rand(1..100)
13 | num2 = rand(1..100)
14 | puts "The numbers are #{num1} and #{num2}"
15 |
16 | avg = (num1 + num2) / 2
17 | puts "The average is " + avg.to_s
18 |
19 | var = variance(num1,num2,avg)
20 | puts "The variance is: " + var.to_s
21 |
22 | puts "The standard dev is " + (std_dev(var).round(2)).to_s
--------------------------------------------------------------------------------
/problems/prob01/prob1es6.js:
--------------------------------------------------------------------------------
1 | const num1 = Math.floor((Math.random() * (100)));
2 | const num2 = Math.floor((Math.random() * (100)));
3 |
4 | const avg = getMean(num1, num2);
5 | const variance = getVariance(num1, num2, avg);
6 | const stdDev = getStdDev(variance);
7 |
8 | console.log(`Numbers: ${num1}, ${num2}`);
9 | console.log(`Mean: ${avg}`);
10 | console.log(`Variance: ${variance}`);
11 | console.log(`Standard Deviation: ${stdDev}`);
12 |
13 | function getMean(num1, num2) {
14 | return (num1 + num2) / 2;
15 | }
16 |
17 | function getVariance(num1, num2 , avg) {
18 | return Math.pow((num1 - avg), 2) + Math.pow((num2 - avg), 2);
19 | }
20 |
21 | function getStdDev(variance) {
22 | return Math.sqrt(variance);
23 | }
24 |
--------------------------------------------------------------------------------
/problems/prob02/prob2.coffee:
--------------------------------------------------------------------------------
1 | rand_n = (n) ->
2 | list = []
3 | i = 1
4 |
5 | while i <= n
6 | list.push Math.floor((Math.random() * 100))
7 | i++
8 | list
9 |
10 | average = (list) ->
11 | average_value = 0
12 | i = 0
13 |
14 | while i < list.length
15 | average_value += Number(list[i])
16 | i++
17 | Math.round average_value / list.length
18 |
19 | variance = (rand_list, average) ->
20 | variance_value = 0
21 | i = 0
22 |
23 | while i < rand_list.length
24 | variance_value += Number(Math.pow((list[i] - avg), 2))
25 | i++
26 | variance_value / rand_list.length
27 |
28 | standard_deviation = (variance) ->
29 | std_dev = Math.sqrt(variance)
30 | Math.round std_dev
31 |
32 | rand_nums = rand_n(10)
33 | console.log "The numbers are " + rand_nums
34 | avg = average(rand_nums)
35 | console.log "The average is " + avg
36 | var_variable = variance(rand_nums, avg)
37 | console.log "The variance is " + var_variable
38 | std_dev = standard_deviation(var_variable)
39 | console.log "The standard dev is " + std_dev
--------------------------------------------------------------------------------
/problems/prob02/prob2.js:
--------------------------------------------------------------------------------
1 | function createList(num) {
2 | var i = 0;
3 | var list = [];
4 | i = 1;
5 | while (i <= num) {
6 | list.push(Math.floor(Math.random() * 100));
7 | i++;
8 | }
9 | return list;
10 | }
11 |
12 | function calculateAverage(list) {
13 | var averageValue = 0;
14 | var i = 0;
15 | while (i < list.length) {
16 | averageValue += Number(list[i]);
17 | i++;
18 | }
19 | return Math.round(averageValue / list.length);
20 | }
21 |
22 | function calculateVariance(list, average) {
23 | var i = 0;
24 | var varianceValue = 0;
25 | while (i < list.length) {
26 | varianceValue += Number(Math.pow(list[i] - avg, 2));
27 | i++;
28 | }
29 | return varianceValue / list.length;
30 | }
31 |
32 | function calcualteStandardDeviation(variance) {
33 | var stdDev = Math.sqrt(variance);
34 | return Math.round(stdDev);
35 | }
36 |
37 |
38 | var list = createList(10);
39 | console.log('The numbers are ' + list);
40 |
41 | var avg = calculateAverage(list);
42 | console.log('The average is ' + avg);
43 |
44 | var variance = calculateVariance(list, avg);
45 | console.log('The variance is ' + variance);
46 |
47 | var stdDev = calcualteStandardDeviation(variance);
48 | console.log('The standard dev is ' + stdDev);
49 |
--------------------------------------------------------------------------------
/problems/prob02/prob2.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 | from math import sqrt
3 |
4 |
5 | def rand_n(n):
6 | lst = []
7 | for i in range(n):
8 | lst.append(randrange(100))
9 | return lst
10 |
11 |
12 | def average(lst):
13 | avg = sum(lst) / len(lst)
14 | return avg
15 |
16 |
17 | def variance(lst, avg):
18 | var_list = []
19 | for num in lst:
20 | var_list.append((num - avg)**2)
21 | variance = sum(var_list) / len(var_list)
22 | return variance
23 |
24 |
25 | def std_dev(variance):
26 | std = sqrt(variance)
27 | return std
28 |
29 | lst = rand_n(10)
30 | print("The numbers are " + str(lst)[1:-1])
31 |
32 | avg = average(lst)
33 | print("The average is " + str(avg))
34 |
35 | var = variance(lst, avg)
36 | print("The variance is " + str(var))
37 |
38 | std = std_dev(var)
39 | print("The standard dev is " + str(round(std, 2)))
40 |
--------------------------------------------------------------------------------
/problems/prob02/prob2.rb:
--------------------------------------------------------------------------------
1 | def rand_n(n)
2 | list = []
3 | n.times do
4 | list << rand(1..100)
5 | end
6 | list
7 | end
8 |
9 | def average(list)
10 | sum = list.inject{|sum,x| sum + x }
11 | avg = sum / list.length()
12 | end
13 |
14 | def variance(list,average)
15 | var_list =[]
16 | list.each do |num|
17 | var_list << ((num - average)**2)
18 | end
19 | variance = var_list.inject{|sum,x| sum + x } / list.length()
20 | end
21 |
22 | def std_dev(variance)
23 | standard_dev = Math.sqrt(variance)
24 | end
25 |
26 | test = rand_n(10)
27 | puts "The numbers are:"
28 | test.each do |num|
29 | print num.to_s + ", "
30 | end
31 |
32 | avgerage = average(test)
33 | puts "\nThe average is " + avgerage.to_s
34 |
35 | var = variance(test,avgerage)
36 | puts "The variance is " + var.to_s
37 |
38 | std = std_dev(var)
39 | puts "The standard dev is " + (std).round.to_s
--------------------------------------------------------------------------------
/problems/prob02/prob2es6.js:
--------------------------------------------------------------------------------
1 | function createList(num) {
2 | const list = [];
3 | for (var i = 1; i < num; i++) {
4 | list.push(Math.floor(Math.random() * 100));
5 | }
6 | return list;
7 | }
8 |
9 | function calculateAverage(list) {
10 | let averageValue = 0;
11 | list.forEach((el) => {
12 | averageValue += Number(el);
13 | });
14 | return Math.round(averageValue / list.length);
15 | }
16 |
17 | function calculateVariance(list, average) {
18 | let varianceValue = 0;
19 | list.forEach((el) => {
20 | varianceValue += Number(Math.pow(el - avg, 2));
21 | });
22 | return varianceValue / list.length;
23 | }
24 |
25 | function calcualteStandardDeviation(variance) {
26 | const stdDev = Math.sqrt(variance);
27 | return Math.round(stdDev);
28 | }
29 |
30 |
31 | const list = createList(10);
32 | console.log(`The numbers are ${list}`);
33 |
34 | const avg = calculateAverage(list);
35 | console.log(`The average is ${avg}`);
36 |
37 | const variance = calculateVariance(list, avg);
38 | console.log(`The variance is ${variance}`);
39 |
40 | const stdDev = calcualteStandardDeviation(variance);
41 | console.log(`The standard dev is ${stdDev}`);
42 |
--------------------------------------------------------------------------------
/problems/prob03/prob3.js:
--------------------------------------------------------------------------------
1 | function createList(num) {
2 | list = [];
3 | for (var i = 1; i <= num; i++) {
4 | list.push(Math.floor((Math.random() * 100)));
5 | }
6 | return list;
7 | }
8 |
9 | function getMax(list) {
10 | return Math.max.apply(Math, list);
11 | }
12 |
13 | function getMin(list) {
14 | return Math.min.apply(Math, list);
15 | }
16 |
17 | var list = createList(20);
18 | console.log("The numbers are " + list);
19 |
20 | var maxNumber = getMax(list);
21 | console.log("The max number is " + maxNumber);
22 |
23 | var minNumber = getMin(list);
24 | console.log("The min number is " + minNumber);
25 |
--------------------------------------------------------------------------------
/problems/prob03/prob3.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 |
3 |
4 | def rand_n(num):
5 | lst = []
6 | for i in range(num):
7 | lst.append(randrange(100))
8 | return lst
9 |
10 |
11 | def max_n(lst):
12 | return max(lst)
13 |
14 |
15 | def min_n(lst):
16 | return min(lst)
17 |
18 |
19 | lst = rand_n(20)
20 | print("The numbers are " + str(lst)[1:-1])
21 |
22 | max_num = max_n(lst)
23 | print("The max number is " + str(max_num))
24 |
25 | min_num = min_n(lst)
26 | print("The min number is " + str(min_num))
27 |
--------------------------------------------------------------------------------
/problems/prob03/prob3.rb:
--------------------------------------------------------------------------------
1 | def rand_n(n)
2 | list = []
3 | n.times do
4 | list << rand(1..100)
5 | end
6 | list
7 | end
8 |
9 | def max(lst)
10 | lst.max
11 | end
12 |
13 | def min(lst)
14 | lst.min
15 | end
16 |
17 | test = rand_n(20)
18 | puts "The numbers are:"
19 | test.each do |num|
20 | print num.to_s + ", "
21 | end
22 |
23 | max_value = max(test)
24 | puts "\nThe max number is: " + max_value.to_s
25 |
26 | max_value = min(test)
27 | puts "The min number is: " + max_value.to_s
28 |
29 |
30 |
--------------------------------------------------------------------------------
/problems/prob03/prob3es6.js:
--------------------------------------------------------------------------------
1 | function createList(num) {
2 | const list = [];
3 | for (var i = 1; i < num; i++) {
4 | list.push(Math.floor(Math.random() * 100));
5 | }
6 | return list;
7 | }
8 |
9 | function getMax(list) {
10 | return Math.max.apply(Math, list);
11 | }
12 |
13 | function getMin(list) {
14 | return Math.min.apply(Math, list);
15 | }
16 |
17 | const list = createList(20);
18 | console.log(`The numbers are - ${list}`);
19 |
20 | const maxNumber = getMax(list);
21 | console.log(`The max number is - ${maxNumber}`);
22 |
23 | const minNumber = getMin(list);
24 | console.log(`The min number is - ${minNumber}`);
25 |
--------------------------------------------------------------------------------
/problems/prob04/prob4.js:
--------------------------------------------------------------------------------
1 | var randPrint = function (randomNumber){
2 | var list = [];
3 | for (var i = 0; i <= randomNumber; i++) {
4 | if (i % 2 === 0){
5 | list.push(i);
6 | }
7 | }
8 | return list;
9 | };
10 |
11 | var randomNumber = (Math.floor((Math.random() * 100)));
12 | console.log("The number is " + randomNumber);
13 | console.log(randPrint(randomNumber));
14 |
15 |
--------------------------------------------------------------------------------
/problems/prob04/prob4.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 |
3 |
4 | def rand_print(num):
5 | array = []
6 | for x in range(0, num + 1):
7 | if x % 2 == 0:
8 | array.append(x)
9 | return array
10 |
11 |
12 | rand_num = randrange(100)
13 | print("The number is " + str(rand_num))
14 | print("")
15 | print(rand_print(rand_num))
16 |
--------------------------------------------------------------------------------
/problems/prob04/prob4.rb:
--------------------------------------------------------------------------------
1 | def rand_print(num)
2 | array = []
3 | (0..num).each do |x|
4 | if x % 2 == 0
5 | array << x
6 | end
7 | end
8 | return array
9 | end
10 |
11 | rand_num = rand(1..100)
12 | puts "The number is " + rand_num.to_s + "\n\n"
13 | puts rand_print(rand_num)
--------------------------------------------------------------------------------
/problems/prob04/prob4es6.js:
--------------------------------------------------------------------------------
1 | function randPrint(randNum) {
2 | const list = [];
3 | for (let i = 0; i <= randomNumber; i++) {
4 | if (i % 2 === 0){
5 | list.push(i);
6 | }
7 | }
8 | return list;
9 | }
10 |
11 | const randomNumber = (Math.floor((Math.random() * 100)));
12 | console.log(`The number is - ${randomNumber}`);
13 | console.log(randPrint(randomNumber));
14 |
--------------------------------------------------------------------------------
/problems/prob05/prob5.js:
--------------------------------------------------------------------------------
1 | function generateList(randNum) {
2 | var list = [];
3 | if (randNum > 40) {
4 | for (var i = 40; i <= randNum; i++) {
5 | if (i % 2 !== 0){
6 | list.push(i);
7 | }
8 | }
9 | } else {
10 | for (var j = 0; j < 40; j++) {
11 | if (j % 2 !== 0) {
12 | list.push(j);
13 | }
14 | }
15 | }
16 | return list;
17 | }
18 |
19 | var randNum = (Math.floor((Math.random() * 100)));
20 | console.log('The number is ' + randNum);
21 | console.log(generateList(randNum));
22 |
--------------------------------------------------------------------------------
/problems/prob05/prob5.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 |
3 |
4 | def generateList(num):
5 | array = []
6 | if num > 40:
7 | for x in range(40, num + 1):
8 | if x % 2 != 0:
9 | array.append(x)
10 | else:
11 | for x in range(0, 40 + 1):
12 | if x % 2 != 0:
13 | array.append(x)
14 | return array
15 |
16 | rand_num = randrange(100)
17 | print("The number is {0}".format(rand_num))
18 | print(generateList(rand_num))
19 |
--------------------------------------------------------------------------------
/problems/prob05/prob5.rb:
--------------------------------------------------------------------------------
1 | def rand_print(num)
2 | array = []
3 | if num > 40
4 | (40..num).each do |x|
5 | if x % 2 != 0
6 | array << x
7 | end
8 | end
9 | else
10 | (0..40).each do |x|
11 | if x % 2 != 0
12 | array << x
13 | end
14 | end
15 | end
16 | return array
17 | end
18 |
19 | rand_num = rand(1..100)
20 | puts "The number is " + rand_num.to_s + "\n"
21 | print rand_print(rand_num)
--------------------------------------------------------------------------------
/problems/prob05/prob5es6.js:
--------------------------------------------------------------------------------
1 | function generateList(randNum) {
2 | const list = [];
3 | let counter = 0;
4 | let upperRange = 40;
5 | if (randNum > 40) {
6 | counter = 40;
7 | upperRange = randNum;
8 | }
9 | for (let i = counter; i < upperRange; i++) {
10 | if (i % 2 !== 0) list.push(i);
11 | }
12 | return list;
13 | }
14 |
15 | const randNum = (Math.floor((Math.random() * 100)));
16 | console.log(`The number is ${randNum}`);
17 | console.log(generateList(randNum));
18 |
--------------------------------------------------------------------------------
/problems/prob06/prob6.js:
--------------------------------------------------------------------------------
1 | function generateList(num){
2 | var greaterThan = [];
3 | var lessThan = [];
4 | if (num > 40) {
5 | for (var i = 40; i <= num; i++) {
6 | if (i % 2 !== 0){
7 | greaterThan.push(i);
8 | }
9 | }
10 | return greaterThan.reverse();
11 | } else {
12 | for (var j = num; j < 40; j++) {
13 | if (j % 2 !== 0) {
14 | lessThan.push(j);
15 | }
16 | }
17 | return lessThan.reverse();
18 | }
19 | }
20 |
21 | var num = (Math.floor((Math.random() * 100)));
22 | console.log("The number is " + num);
23 | console.log(generateList(num));
24 |
--------------------------------------------------------------------------------
/problems/prob06/prob6.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 |
3 |
4 | def generate_list(num):
5 | greater_than = []
6 | less_than = []
7 | if num > 40:
8 | for x in range(40, num + 1):
9 | if x % 2 != 0:
10 | greater_than.append(x)
11 | return greater_than
12 | else:
13 | for x in range(0, num + 1):
14 | if x % 2 != 0:
15 | less_than.append(x)
16 | return less_than
17 |
18 |
19 | def reverse(lst):
20 | reverse_list = []
21 | for i in reversed(lst):
22 | reverse_list.append(i)
23 | return reverse_list
24 |
25 |
26 | rand_num = randrange(100)
27 | print("The number is {0}".format(rand_num))
28 | print(reverse(generate_list(rand_num)))
29 |
--------------------------------------------------------------------------------
/problems/prob06/prob6.rb:
--------------------------------------------------------------------------------
1 | def rand_print(num)
2 | greater_than = []
3 | less_than = []
4 | if num > 40
5 | (40..num).each do |x|
6 | if x % 2 != 0
7 | greater_than << x
8 | end
9 | end
10 | return greater_than.reverse
11 | else
12 | (0..num).each do |x|
13 | if x % 2 != 0
14 | less_than << x
15 | end
16 | end
17 | return less_than.reverse
18 | end
19 | end
20 |
21 | rand_num = rand(1..100)
22 | puts "The number is " + rand_num.to_s + "\n\n"
23 | print rand_print(rand_num)
--------------------------------------------------------------------------------
/problems/prob06/prob6es6.js:
--------------------------------------------------------------------------------
1 | function generateList(num) {
2 | const list = [];
3 | let counter = 40;
4 | let upperRange = num + 1;
5 | if (num <= 40) {
6 | counter = num;
7 | upperRange = 40;
8 | }
9 | for (let i = counter; i < upperRange; i++) {
10 | if (i % 2 !== 0) list.push(i);
11 | }
12 | return list.reverse();
13 | }
14 |
15 | const num = (Math.floor((Math.random() * 100)));
16 | console.log(`The number is ${num}`);
17 | console.log(generateList(num));
18 |
--------------------------------------------------------------------------------
/problems/prob07/js/js/main.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Write a function that takes a dollar amount and a discount percentage and returns the total discount amount. Return a warning if the discount amount is greater than 100 or less than 0 percent. Test the results with mocha and chai.
4 |
5 | */
6 |
7 |
8 | // brute force!
9 | function discount(totalAmount, discountPecentage) {
10 | if (discountPecentage > 100 || discountPecentage < 0) {
11 | return "That discount is not acceptable!";
12 | }
13 | return totalAmount * (discountPecentage * 0.01);
14 | }
15 |
16 | // quick tests!
17 | console.log(discount(100, 10) === 10);
18 | console.log(discount(100, 100) === 100);
19 | console.log(discount(100, 0) === 0);
20 |
21 | console.log(discount(100, 101) === "That discount is not acceptable!");
22 | console.log(discount(100, -1) === "That discount is not acceptable!");
23 |
--------------------------------------------------------------------------------
/problems/prob07/js/test/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/problems/prob07/js/test/test.js:
--------------------------------------------------------------------------------
1 | var expect = chai.expect;
2 | // var should = chai.should();
3 |
4 | // sample!
5 | // describe('Compare Numbers', function() {
6 | // it('1 should equal 1', function() {
7 | // expect(1).to.equal(1);
8 | // });
9 | // });
10 |
11 | // edge cases? what else should be tested?
12 |
13 | describe('Discount Percentage', function() {
14 | it('should equal 10 if 100 is the total and 10 is the discount', function() {
15 | expect(discount(100, 10)).to.equal(10);
16 | });
17 | it('should equal 100 if 100 is the total and 100 is the discount', function() {
18 | expect(discount(100, 100)).to.equal(100);
19 | });
20 | it('should equal 0 if 100 is the total and 0 is the discount', function() {
21 | expect(discount(100, 0)).to.equal(0);
22 | });
23 | it('should equal "That discount is not acceptable!" if 100 is the total and 101 is the discount', function() {
24 | expect(discount(100, 101)).to.equal("That discount is not acceptable!");
25 | });
26 | it('should equal "That discount is not acceptable!" if 100 is the total and -1 is the discount', function() {
27 | expect(discount(100, -1)).to.equal("That discount is not acceptable!");
28 | });
29 | });
30 |
--------------------------------------------------------------------------------
/problems/prob07/prob7.py:
--------------------------------------------------------------------------------
1 | def discount(total, percent):
2 | if percent > 100 or percent < 0:
3 | return "Sorry. Enter a valid percent."
4 | else:
5 | the_discount = total * (percent * .01)
6 | return round(the_discount, 2)
7 |
8 | print(discount(100, 10) == 10.00)
9 | print(discount(90, 90) == 81.00)
10 | print(discount(87.9, 91.6) == 80.52)
11 | print(discount(90, -1) == "Sorry. Enter a valid percent.")
12 |
--------------------------------------------------------------------------------
/problems/prob07/prob7.rb:
--------------------------------------------------------------------------------
1 | def discount(total, percent)
2 | if percent > 100 or percent < 0
3 | return "Sorry. Enter a valid percent."
4 | else
5 | the_discount = total * (percent * 0.01)
6 | return the_discount.round(2)
7 | end
8 | end
9 |
10 | puts discount(100,10) == 10.00
11 | puts discount(90, 90) == 81.00
12 | puts discount(87.9, 91.6) == 80.52
13 | puts discount(90,-1) == "Sorry. Enter a valid percent."
14 |
--------------------------------------------------------------------------------
/problems/prob08/js/js/main.js:
--------------------------------------------------------------------------------
1 | var Discount = function(totalAmount, discountPecentage) {
2 | this.totalAmount = totalAmount;
3 | this.discountPecentage = discountPecentage;
4 | };
5 |
6 | Discount.prototype.calcDiscount = function() {
7 | if (this.discountPecentage > 100 || this.discountPecentage < 0) {
8 | return "That discount is not acceptable!";
9 | }
10 | return this.totalAmount * (this.discountPecentage * 0.01);
11 | };
12 |
13 | // quick tests!
14 | console.log(new Discount(100, 10).calcDiscount() === 10);
15 | console.log(new Discount(100, 100).calcDiscount() === 100);
16 | console.log(new Discount(100, 0).calcDiscount() === 0);
17 |
18 | console.log(
19 | new Discount(100, 101).calcDiscount() === "That discount is not acceptable!");
20 | console.log(
21 | new Discount(100, -1).calcDiscount() === "That discount is not acceptable!");
22 |
--------------------------------------------------------------------------------
/problems/prob08/js/test/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/problems/prob08/js/test/test.js:
--------------------------------------------------------------------------------
1 | var expect = chai.expect;
2 |
3 | describe('Discount Percentage', function() {
4 | it('should equal 10 if 100 is the total and 10 is the discount', function() {
5 | expect(new Discount(100, 10).calcDiscount()).to.equal(10);
6 | });
7 | it('should equal 100 if 100 is the total and 100 is the discount', function() {
8 | expect(new Discount(100, 100).calcDiscount()).to.equal(100);
9 | });
10 | it('should equal 0 if 100 is the total and 0 is the discount', function() {
11 | expect(new Discount(100, 0).calcDiscount()).to.equal(0);
12 | });
13 | it('should equal "That discount is not acceptable!" if 100 is the total and 101 is the discount', function() {
14 | expect(new Discount(100, 101).calcDiscount()).to.equal(
15 | "That discount is not acceptable!");
16 | });
17 | it('should equal "That discount is not acceptable!" if 100 is the total and -1 is the discount', function() {
18 | expect(new Discount(100, -1).calcDiscount()).to.equal(
19 | "That discount is not acceptable!");
20 | });
21 | });
22 |
--------------------------------------------------------------------------------
/problems/prob08/prob8.py:
--------------------------------------------------------------------------------
1 | class Discount:
2 | @staticmethod
3 | def calc_discount(total, percent):
4 | if percent > 100 or percent < 0:
5 | return "Sorry. Enter a valid percent."
6 | else:
7 | the_discount = total * (percent * .01)
8 | return round(the_discount, 2)
9 |
10 |
11 | # discount1 = Discount()
12 | # print discount1.calc_discount(100,10)
13 | # print discount1.calc_discount(90,90)
14 | # print discount1.calc_discount(87.9,91.6)
15 | # print discount1.calc_discount(90,-1)
16 |
--------------------------------------------------------------------------------
/problems/prob08/prob8.rb:
--------------------------------------------------------------------------------
1 | class Discount
2 |
3 | def initialize(total,percent)
4 | @total = total
5 | @percent = percent
6 | end
7 |
8 |
9 | def calc_discount()
10 | if @percent > 100 or @percent < 0
11 | return "Sorry. Enter a valid percent."
12 | else
13 | the_discount = @total * (@percent * 0.01)
14 | return the_discount.round(2)
15 | end
16 | end
17 |
18 | end
19 |
20 |
21 | # discount1 = Discount.new(100,10)
22 | # puts discount1.calc_discount()
23 |
24 | # discount2 = Discount.new(90,90)
25 | # puts discount2.calc_discount()
26 |
27 | # discount3 = Discount.new(87.9,91.6)
28 | # puts discount3.calc_discount()
29 |
30 | # discount4 = Discount.new(90,-1)
31 | # puts discount4.calc_discount()
--------------------------------------------------------------------------------
/problems/prob08/prob8_test.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | from prob8 import Discount
3 |
4 |
5 | class DiscountTest(unittest.TestCase):
6 |
7 | def test_pass(self):
8 | discount1 = Discount()
9 | self.assertEqual(discount1.calc_discount(100, 10), 10.0)
10 |
11 | def test_fail(self):
12 | discount1 = Discount()
13 | self.assertEqual(
14 | discount1.calc_discount(100, -1),
15 | 'Sorry. Enter a valid percent.'
16 | )
17 |
18 | if __name__ == '__main__':
19 | unittest.main()
20 |
--------------------------------------------------------------------------------
/problems/prob08/prob8_test.rb:
--------------------------------------------------------------------------------
1 | require './prob8.rb'
2 |
3 | #---- to run ---- #
4 | # $ rspec prob8_test.rb -c -fd
5 |
6 |
7 | describe Discount do
8 |
9 | before do
10 | @discount1 = Discount.new(100,10)
11 | @discount1.calc_discount()
12 | @discount2 = Discount.new(90,-1)
13 | @discount2.calc_discount()
14 | end
15 |
16 | describe '#pass' do
17 | it 'should return the discount amount' do
18 | @discount1.calc_discount()
19 | @discount1.calc_discount.should eql 10.0
20 | end
21 | end
22 |
23 | describe '#fail' do
24 | it 'should return an error message' do
25 | @discount2.calc_discount()
26 | @discount2.calc_discount.should eql "Sorry. Enter a valid percent."
27 | end
28 | end
29 |
30 | end
31 |
32 |
--------------------------------------------------------------------------------
/problems/prob09/prob9.coffee:
--------------------------------------------------------------------------------
1 | rand_nums = []
2 |
3 | generate_random = (num) ->
4 | i = 0
5 |
6 | while i <= num
7 | rand_nums.push Math.floor((Math.random() * 100))
8 | i++
9 | document.write rand_nums.sort() + " "
10 |
11 | generate_random(10)
12 | rand_nums = []
13 | generate_random(20)
14 | rand_nums = []
15 | generate_random(5)
--------------------------------------------------------------------------------
/problems/prob09/prob9.js:
--------------------------------------------------------------------------------
1 | var generateRandom = function (num){
2 | for (var i = 0; i <= num; i++) {
3 | randNums.push(Math.floor((Math.random() * 100)));
4 | }
5 | return randNums.sort();
6 | };
7 |
8 | var randNums = [];
9 | console.log(generateRandom(10));
10 |
11 | randNums = [];
12 | console.log(generateRandom(20));
13 |
14 | randNums = [];
15 | console.log(generateRandom(5));
16 |
--------------------------------------------------------------------------------
/problems/prob09/prob9.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 |
3 |
4 | # generate n random numbers
5 | def generate_random(num):
6 | rand_nums = []
7 | for x in range(0, num):
8 | rand_nums.append(randrange(100))
9 | return sorted(rand_nums)
10 |
11 | print(generate_random(10))
12 | print(generate_random(20))
13 | print(generate_random(5))
14 |
--------------------------------------------------------------------------------
/problems/prob09/prob9.rb:
--------------------------------------------------------------------------------
1 | def generate_random(num)
2 | rand_nums = []
3 | (0..num).each do |x|
4 | rand_nums << rand(1..100)
5 | end
6 | return rand_nums.sort
7 | end
8 |
9 |
10 | print generate_random(10)
11 | puts
12 | print generate_random(20)
13 | puts
14 | print generate_random(5)
15 |
--------------------------------------------------------------------------------
/problems/prob09/prob9es6.js:
--------------------------------------------------------------------------------
1 | function generateRandom(num) {
2 | const randNums = [];
3 | for (let i = 0; i <= num; i++) {
4 | randNums.push(Math.floor((Math.random() * 100)));
5 | }
6 | return randNums.sort();
7 | }
8 |
9 | console.log(generateRandom(10));
10 | console.log(generateRandom(20));
11 | console.log(generateRandom(5));
12 |
--------------------------------------------------------------------------------
/problems/prob10/prob10.js:
--------------------------------------------------------------------------------
1 | function randSum(num) {
2 | let total = 0;
3 | const numArr = num.toString().split('');
4 | for (let num of numArr) {
5 | total += parseInt(num);
6 | }
7 | return total;
8 | }
9 |
10 | const randomNumber = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
11 | console.log(`The number is ${randomNumber}`);
12 | console.log(`The sum of its digits is ${randSum(randomNumber)}`);
13 |
--------------------------------------------------------------------------------
/problems/prob10/prob10.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 |
3 |
4 | def rand_sum(num):
5 | total = 0
6 | for x in str(num):
7 | total += int(x)
8 | return total
9 |
10 | rand_num = randrange(1000, 9999)
11 | print("The number is " + str(rand_num))
12 | print("The sum of its digits is " + str(rand_sum(rand_num)))
13 |
--------------------------------------------------------------------------------
/problems/prob10/prob10.rb:
--------------------------------------------------------------------------------
1 | def rand_sum(num)
2 | total = 0
3 | (num.to_s).each_char do |x|
4 | total += (x.to_i)
5 | end
6 | return total
7 | end
8 |
9 | rand_num = rand(1000..9999)
10 | puts "The number is " + rand_num.to_s + "\n"
11 | puts "The sum of its digits is " + (rand_sum(rand_num)).to_s
12 |
--------------------------------------------------------------------------------
/problems/prob11/prob11.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Generate a random number from 1000 to 9999 and output the sum of its digits, repeatedly, dropping the left-most digit after each iteration, until there is only one digit only. For example, if the number is 1049, then the output should be 14, 13, 13, 9.
4 |
5 | */
6 |
7 | function getTotal(num) {
8 | let total = 0;
9 | const numArr = num.toString().split('');
10 | for (let num of numArr) {
11 | total += parseInt(num);
12 | }
13 | return total;
14 | }
15 |
16 | function dropDigit(num) {
17 | const numArray = num.toString().split('');
18 | numArray.reverse().pop();
19 | return numArray.reverse().join('');
20 | }
21 |
22 | function output(num) {
23 | while (num.toString().length > 0) {
24 | console.log(getTotal(num));
25 | return output(dropDigit(num));
26 | }
27 | }
28 |
29 | const randomNumber = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
30 | console.log(`The number is ${randomNumber}`);
31 | output(randomNumber);
32 |
--------------------------------------------------------------------------------
/problems/prob11/prob11.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 |
3 |
4 | def convert_to_array(num):
5 | lst = [int(i) for i in str(num)]
6 | total(lst)
7 |
8 |
9 | def total(array):
10 | while len(array) > 0:
11 | print(sum(array))
12 | del array[0]
13 |
14 | rand_num = randrange(1000, 9999)
15 | print("The number is " + str(rand_num))
16 | convert_to_array(rand_num)
17 |
--------------------------------------------------------------------------------
/problems/prob11/prob11.rb:
--------------------------------------------------------------------------------
1 | def convert_to_array(num)
2 | lst = num.to_s.split('').map(&:to_i)
3 | total(lst)
4 | end
5 |
6 | def total(array)
7 | sum = 0
8 | while array.length > 0
9 | p array.inject(:+)
10 | array.shift
11 | end
12 | end
13 |
14 | rand_num = rand(1000..9999)
15 | puts "The number is " + rand_num.to_s + "\n"
16 | convert_to_array(rand_num)
17 |
18 |
19 |
--------------------------------------------------------------------------------
/problems/prob12/js/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/problems/prob12/js/main.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Generate two random integers from 0 to 100 and output the smallest number such that each shares a least common denominator (aside for 1). For example, 18 and 6 should return 6, while 9 and 4 should return False. Return False if the two numbers are equal.
4 |
5 | */
6 |
7 | function calculate(num1, num2) {
8 | if (num1 % 7 === 0 && num2 % 7 === 0) {
9 | return smallerNum(num1, num2);
10 | }
11 | else if (num1 % 5 === 0 && num2 % 5 === 0) {
12 | return smallerNum(num1, num2);
13 | }
14 | else if (num1 % 3 === 0 && num2 % 3 === 0) {
15 | return smallerNum(num1, num2);
16 | }
17 | else if (num1 % 2 === 0 && num2 % 2 === 0) {
18 | return smallerNum(num1, num2);
19 | }
20 | else {
21 | return false;
22 | }
23 | }
24 |
25 | function smallerNum(num1, num2) {
26 | if (num1 > num2) return num2;
27 | if (num2 > num1) return num1;
28 | return false;
29 | }
30 |
31 | const num1 = Math.floor((Math.random() * 100));
32 | const num2 = Math.floor((Math.random() * 100));
33 | console.log(`The numbers are ${num1} and ${num2}`);
34 | console.log(calculate(num1, num2));
35 |
--------------------------------------------------------------------------------
/problems/prob12/js/test.js:
--------------------------------------------------------------------------------
1 | const expect = chai.expect;
2 |
3 | describe('Least Common Denominator', () => {
4 | describe('smallerNum(96, 93)', () => {
5 | it('should return 93', () => {
6 | expect(smallerNum(96, 93)).to.equal(93);
7 | });
8 | });
9 | describe('smallerNum(80, 80)', () => {
10 | it('should return false', () => {
11 | expect(smallerNum(80, 80)).to.equal(false);
12 | });
13 | });
14 | describe('smallerNum(98, 44)', () => {
15 | it('should return 44', () => {
16 | expect(smallerNum(98, 44)).to.equal(44);
17 | });
18 | });
19 | describe('calculate(18, 6)', () => {
20 | it('should return 6', () => {
21 | expect(calculate(18, 6)).to.equal(6);
22 | });
23 | });
24 | describe('calculate(80, 80)', () => {
25 | it('should return false', () => {
26 | expect(calculate(80, 80)).to.equal(false);
27 | });
28 | });
29 | describe('calculate(9, 4)', () => {
30 | it('should return false', () => {
31 | expect(calculate(9, 4)).to.equal(false);
32 | });
33 | });
34 | });
35 |
--------------------------------------------------------------------------------
/problems/prob12/prob12.rb:
--------------------------------------------------------------------------------
1 | def gcd(n1,n2)
2 | n1,n2 = n2,n1 if n1 < n2
3 | n1,n2 = n2,n1%n2 while n1%n2 != 0
4 | return n2
5 | end
6 |
7 | def smaller_num(x, y)
8 | if x > y
9 | return y
10 | elsif x == y
11 | return false
12 | else
13 | return x
14 | end
15 | end
16 |
17 |
18 | rand_num1 = rand(1..100)
19 | rand_num2 = rand(1..100)
20 | puts "The numbers are " + (rand_num1.to_s) + " and " + (rand_num2.to_s)
21 |
22 | if gcd(rand_num1,rand_num2) > 1
23 | puts smaller_num(rand_num1, rand_num2)
24 | else
25 | puts false
26 | end
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/problems/prob12/prob12a.py:
--------------------------------------------------------------------------------
1 | # brute force
2 |
3 | from random import randrange
4 |
5 |
6 | def calculate(num1, num2):
7 | if num1 % 7 == 0 and num2 % 7 == 0:
8 | return smaller_num(num1, num2)
9 | elif num1 % 5 == 0 and num2 % 5 == 0:
10 | return smaller_num(num1, num2)
11 | elif num1 % 3 == 0 and num2 % 3 == 0:
12 | return smaller_num(num1, num2)
13 | elif num1 % 2 == 0 and num2 % 2 == 0:
14 | return smaller_num(num1, num2)
15 | else:
16 | return False
17 |
18 |
19 | def smaller_num(x, y):
20 | if x > y:
21 | return y
22 | elif x == y:
23 | return False
24 | else:
25 | return x
26 |
27 | rand_num1 = randrange(1, 100)
28 | rand_num2 = randrange(1, 100)
29 | print("The numbers are " + str(rand_num1) + " and " + str(rand_num2))
30 | print(calculate(rand_num1, rand_num2))
31 |
--------------------------------------------------------------------------------
/problems/prob12/prob12b.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 |
3 |
4 | # Euclid's Algorithm
5 | def gcd(num1, num2):
6 | while num2:
7 | num1, num2 = num2, num1 % num2
8 | return num1
9 |
10 |
11 | def smaller_num(x, y):
12 | if x > y:
13 | return y
14 | elif x == y:
15 | return False
16 | else:
17 | return x
18 |
19 |
20 | rand_num1 = randrange(1, 100)
21 | rand_num2 = randrange(1, 100)
22 | print("The numbers are " + str(rand_num1) + " and " + str(rand_num2))
23 |
24 | if gcd(rand_num1, rand_num2) > 1:
25 | print(smaller_num(rand_num1, rand_num2))
26 | else:
27 | print(False)
28 |
--------------------------------------------------------------------------------
/problems/prob13/prob13.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Write a function that takes two random integers as arguments and returns the least common multiple.
4 |
5 | */
6 |
7 | function lcm(num1, num2) {
8 | return (num1 * num2) / gcd(num1, num2);
9 | }
10 |
11 | function gcd(num1, num2) {
12 | return !num2 ? num1 : gcd(num2, num1 % num2);
13 | }
14 |
15 | const num1 = Math.floor((Math.random() * 100));
16 | const num2 = Math.floor((Math.random() * 100));
17 | console.log(`The numbers are ${num1} and ${num2}`);
18 | console.log(lcm(num1, num2));
19 |
--------------------------------------------------------------------------------
/problems/prob13/prob13.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 |
3 |
4 | def lcm(num1, num2):
5 | return num1 * num2 // gcd(num1, num2)
6 |
7 |
8 | def gcd(num1, num2):
9 | while num2:
10 | num1, num2 = num2, num1 % num2
11 | return num1
12 |
13 | rand1 = randrange(1, 100)
14 | rand2 = randrange(1, 100)
15 | print("The numbers are " + str(rand1) + " and " + str(rand2))
16 | print(lcm(rand1, rand2))
17 |
--------------------------------------------------------------------------------
/problems/prob14/prob14.js:
--------------------------------------------------------------------------------
1 | var calculatePower = function (num1, num2) {
2 | var total = 1;
3 | for (var i = 0; i < num2; i++) {
4 | total *= num1;
5 | }
6 | return total;
7 | };
8 |
9 | // or -
10 |
11 | // var calculatePower = function (num1, num2) {
12 | // var i = 0;
13 | // while (i < num2) {
14 | // total *= num1;
15 | // i++;
16 | // }
17 | // return total;
18 | // }
19 |
20 |
21 | var rand1 = Math.floor((Math.random() * 20));
22 | var rand2 = Math.floor((Math.random() * 20));
23 | console.log("What is " + rand1.toString() + " to the " + rand2.toString() + " power?");
24 | console.log("Answer: " + calculatePower(rand1, rand2));
25 |
--------------------------------------------------------------------------------
/problems/prob14/prob14es6.js:
--------------------------------------------------------------------------------
1 | function calculatePower(num1, num2) {
2 | let total = 1;
3 | for (let i = 0; i < num2; i++) {
4 | total *= num1;
5 | }
6 | return total;
7 | }
8 |
9 |
10 | const rand1 = Math.floor((Math.random() * 20));
11 | const rand2 = Math.floor((Math.random() * 20));
12 | console.log(`What is ${rand1} to the ${rand2} power?`);
13 | console.log(`Answer: ${calculatePower(rand1, rand2)}`);
14 |
--------------------------------------------------------------------------------
/problems/prob15/prob15.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Write a function that takes a single number as an input and returns that many lines.
4 | On the first line there is one '#' character.
5 | On the second there are two. And so on.
6 | This will create a nice triangle.
7 |
8 | */
9 |
10 |
11 | function createTriangle(num) {
12 | var line = '';
13 | var i = 0;
14 | while (i < num) {
15 | line += '#';
16 | console.log(line);
17 | i++;
18 | }
19 | }
20 |
21 | createTriangle(10);
22 |
--------------------------------------------------------------------------------
/problems/prob15/prob15es6.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Write a function that takes a single number as an input and returns that many lines.
4 | On the first line there is one '#' character.
5 | On the second there are two. And so on.
6 | This will create a nice triangle.
7 |
8 | */
9 |
10 |
11 | function createTriangle(num) {
12 | var line = '';
13 | for (var i = 0; i < num; i++) {
14 | line += '#';
15 | console.log(line);
16 | }
17 | }
18 |
19 | createTriangle(10);
20 |
--------------------------------------------------------------------------------
/problems/prob16/prob16.js:
--------------------------------------------------------------------------------
1 | function randomString(num) {
2 | var text = '';
3 | var letters = 'abcdefghijklmnopqrstuvwxyz';
4 | for(var i=0; i <= num; i++ )
5 | text += letters.charAt(Math.floor(Math.random() * letters.length));
6 | return text;
7 | }
8 |
9 | function charTest(string1, string2) {
10 | if (string1 === string2) {
11 | return true;
12 | } else {
13 | return false;
14 | }
15 | }
16 |
17 | var randString1 = randomString(10);
18 | var randString2 = randomString(10);
19 | console.log('The strings are ' + randString1 + ' and ' + randString2);
20 | console.log(charTest(randString1, randString2));
21 |
--------------------------------------------------------------------------------
/problems/prob16/prob16es6.js:
--------------------------------------------------------------------------------
1 | function randomString(num) {
2 | let text = '';
3 | const letters = 'abcdefghijklmnopqrstuvwxyz';
4 | for(var i=0; i <= num; i++ )
5 | text += letters.charAt(Math.floor(Math.random() * letters.length));
6 | return text;
7 | }
8 |
9 | function charTest(string1, string2) {
10 | if (string1 === string2) return true;
11 | return false;
12 | }
13 |
14 | const randString1 = randomString(10);
15 | const randString2 = randomString(10);
16 | console.log('The strings are ' + randString1 + ' and ' + randString2);
17 | console.log(charTest(randString1, randString2));
18 | console.log(charTest('test', 'test'));
19 |
--------------------------------------------------------------------------------
/problems/prob17/prob17.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Bootstrap Boilerplate Template
5 |
6 |
7 |
8 |
9 |
13 |
16 |
17 |
18 |
I'm in love with . He's so ! He has big flat , and when our meet, I get in my stomach. I've fallen for him like a ton of , and he shuffles for me, too. But I think he's got another girlfriend. What should I do?
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/problems/prob36/prob36.js:
--------------------------------------------------------------------------------
1 | function countZeros(array) {
2 | var count = 0;
3 | for (var i = 0; i < array.length; i++) {
4 | array[i] === 0 ? count++ : null;
5 | }
6 | return count;
7 | }
8 |
9 | console.log(countZeros([0,1,0,2,3]))
10 | console.log(countZeros([0,1,0,0,0]))
11 | console.log(countZeros([0]))
12 |
13 |
14 | //** refactor with a helper function */
15 |
16 | function countZerosHelper(array) {
17 | var count = 0;
18 | for (var i = 0; i < array.length; i++) {
19 | hasZeros(array[i]) === true ? count++ : null;
20 | }
21 | return count;
22 | }
23 |
24 | function hasZeros(integer){
25 | integer === 0 ? true : false;
26 | }
27 |
28 | console.log(countZerosHelper([0,1,0,2,3]))
29 | console.log(countZerosHelper([0,1,0,0,0]))
30 | console.log(countZerosHelper([0]))
--------------------------------------------------------------------------------
/problems/prob36/prob36.rb:
--------------------------------------------------------------------------------
1 | def count_zeros(array)
2 | count = 0
3 | array.each { |int| int == 0 ? count +=1 : nil }
4 | return count
5 | end
6 |
7 | puts count_zeros([0,1,0,2,3]) == 2
8 | puts count_zeros([0,1,0,0,0]) == 4
9 | puts count_zeros([0]) == 1
10 |
11 | ### -- refactured with a helper function -- ###
12 |
13 | def count_zeros_with_helpers(array)
14 | count = 0
15 | array.each { |int| has_zeros(int) == true ? count +=1 : nil}
16 | return count
17 | end
18 |
19 | def has_zeros(num)
20 | num == 0 ? true : false
21 | end
22 |
23 | puts count_zeros_with_helpers([0,1,0,2,3]) == 2
24 | puts count_zeros_with_helpers([0,1,0,0,0]) == 4
25 | puts count_zeros_with_helpers([0]) == 1
26 |
--------------------------------------------------------------------------------
/problems/prob37/prob37.js:
--------------------------------------------------------------------------------
1 | function processParagraph(paragraph) {
2 | var array = paragraph.split(" ")
3 | for (var i = 0; i < array.length; i++) {
4 | if (array[i].charAt(0) === "%" && array[i].charAt(1)) {
5 | return console.log("This is an H1:" + paragraph.slice(("%", 2)))
6 | } else if (array[i].charAt(0) === "%") {
7 | return console.log("This is an HX:" + paragraph.slice(("%", 1)))
8 | } else {
9 | return console.log("This is a p: " + paragraph)
10 | }
11 | }
12 | }
13 |
14 | var p1 = "% The Book of Programming"
15 | var p2 = "%% The Two Aspects"
16 | var p3 = "Below the surface of the machine, the program moves. Without effort," +
17 | "it expands and contracts. In great harmony, electrons scatter and" +
18 | "regroup. The forms on the monitor are but ripples on the water. The" +
19 | "essence stays invisibly below."
20 |
21 | processParagraph(p1)
22 | processParagraph(p2)
23 | processParagraph(p3)
24 |
25 |
26 | // http://jsfiddle.net/mjhea0/mpbrx/
--------------------------------------------------------------------------------
/problems/prob38/prob38.js:
--------------------------------------------------------------------------------
1 | function splitParagraph(string) {
2 | return string.split(" ")
3 | }
4 |
5 | console.log(splitParagraph("happy birthday to you happy birthday to you"))
6 |
7 | // http://jsfiddle.net/mjhea0/9bMnd/1/
--------------------------------------------------------------------------------
/problems/prob38/prob38.rb:
--------------------------------------------------------------------------------
1 | def splitParagraph(string)
2 | string.split(" ")
3 | end
4 |
5 | p splitParagraph("happy birthday to you happy birthday to you") == ["happy", "birthday", "to", "you", "happy", "birthday", "to", "you"]
--------------------------------------------------------------------------------
/problems/prob39/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {{Title}}
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
Guessing Game!
15 |
Rules: You are going to set a number for the computer to guess, and the computer will also pick a number for you to guess. You will take turns guessing, and the first to guess their opponent's number wins.
16 |
17 |
24 |
25 |
The computer is aiming for your pick of {{userPickedNum}}.
26 |
27 |
28 |
29 |
The computer guessed {{compGuessNum}}.
30 |
31 |
32 |
33 |
34 |
35 |
36 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
You guessed {{userNumber}}.
49 | That guess is {{proximity}}
50 |
51 |
52 |
The computer chose {{compNum}}.
53 |
54 | {{gameResult}}
55 |
56 |
57 |
58 |
59 |
User Wins: {{userWins}}
60 |
Computer Wins : {{compWins}}
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
--------------------------------------------------------------------------------
/problems/prob39/main.css:
--------------------------------------------------------------------------------
1 | body {
2 | text-align: center;
3 | }
4 |
--------------------------------------------------------------------------------
/problems/prob39/main.js:
--------------------------------------------------------------------------------
1 | var app = angular.module("guessApp", []);
2 |
3 | app.controller("GuessController", function($scope) {
4 |
5 | $scope.compNum = getNumber(1, 100);
6 | $scope.compGuessNum = getNumber(1, 100);
7 | $scope.title = "Guessing Game!";
8 | $scope.userWins = 0;
9 | $scope.compWins = 0;
10 |
11 | $scope.pickNum = function(){
12 | $scope.compNum = getNumber(1, 100);
13 | };
14 |
15 | $scope.setUserNum = function(){
16 | $scope.userPicked = true;
17 | };
18 |
19 | //AI
20 | var max = 100;
21 | var min = 1;
22 |
23 | $scope.userGuess = function(){
24 | //check user guess
25 | if($scope.userNum === $scope.compNum){
26 | $scope.win = $scope.guess = true;
27 | $scope.userNumber = $scope.userNum;
28 | $scope.proximity = 'correct!';
29 | $scope.gameResult = 'You win!';
30 | $scope.userWins = +$scope.userWins + 1;
31 | }
32 | else if($scope.userNum > $scope.compNum){
33 | $scope.guess = true;
34 | $scope.userNumber = $scope.userNum;
35 | $scope.proximity = "too high.";
36 | }
37 | else{
38 | $scope.guess = true;
39 | $scope.userNumber = $scope.userNum;
40 | $scope.proximity = "too low.";
41 | }
42 |
43 | //check comp guess
44 | if($scope.compGuessNum === $scope.userPickedNum){
45 | $scope.win = true;
46 | $scope.gameResult = 'Computer Wins.';
47 | $scope.compWins = $scope.compWins + 1;
48 | }
49 | else if($scope.compGuessNum > $scope.userPickedNum){
50 | //gives comp a new max
51 | max = $scope.compGuessNum;
52 | $scope.compGuessNum = getNumber (+max, +min);
53 | }
54 | else{
55 | //gives comp a new min
56 | min = $scope.compGuessNum;
57 | $scope.compGuessNum = getNumber (+max, +min);
58 | }
59 | };
60 |
61 | $scope.startOver = function(){
62 | $scope.win = $scope.guess = $scope.userPicked = false;
63 | $scope.compNum = getNumber(1, 100);
64 | $scope.userPickedNum = $scope.userNum = '';
65 | };
66 |
67 | });
68 |
69 |
70 | //helper functions
71 |
72 | function getNumber (max, min){
73 | var random = Math.floor(Math.random() * (max - min + 1)) + min;
74 | return random;
75 | }
76 |
--------------------------------------------------------------------------------
/problems/prob40/main.js:
--------------------------------------------------------------------------------
1 | /** Find missing integer in a set from 1-10 */
2 |
3 | function oneMissing(arr) {
4 |
5 | // sort array
6 | var sortedArray = arr.slice(0).sort(function(a, b) {return a - b;});
7 |
8 |
9 | // *** functional approach ** //
10 |
11 | var missing = sortedArray.filter(function(num, i){
12 | return sortedArray[i+1] - num > 1;
13 | }).map(function(num){
14 | return num +1;
15 | });
16 |
17 | return missing;
18 |
19 | // *** procedural ** //
20 |
21 | // var missing = [];
22 | // for (var i = 0; i < sortedArray.length; i++) {
23 | // if(sortedArray[i+1] - sortedArray[i] > 1) {
24 | // missing.push(sortedArray[i]+1);
25 | // }
26 | // }
27 |
28 | // return missing;
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/problems/prob41/main.js:
--------------------------------------------------------------------------------
1 | (function() {
2 |
3 | 'use strict';
4 |
5 | module.exports = function (arr) {
6 | return arr.reduce(function(num1, num2) {
7 | return num1 ^ num2;
8 | }, 0);
9 | };
10 |
11 | }());
12 |
13 | // assumes the array is sorted
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/problems/prob42/boom.js:
--------------------------------------------------------------------------------
1 | // thanks https://github.com/bwreid!
2 |
3 | function findSwitchableNumber (numArr, lastNum) {
4 | for ( var i = (numArr.length - 1); i > 0; i-- ) {
5 | if ( parseInt(lastNum[1]) > parseInt(numArr[i-1]) ) {
6 | return [i-1,numArr[i-1]];
7 | }
8 | }
9 | }
10 |
11 | function sortRemainingNumbers ( numArr, switchLeftIndex ) {
12 | var leftSide = numArr.splice(switchLeftIndex + 1);
13 | return numArr.concat( leftSide.sort() ).join('');
14 | }
15 |
16 | function nextNum (numStr) {
17 | numArr = numStr.split('');
18 |
19 | var lastIndex = numArr.length - 1;
20 | var lastNum = [lastIndex, numArr[lastIndex]];
21 | var switchLeft = findSwitchableNumber ( numArr, lastNum );
22 |
23 | if ( !switchLeft ) { return 'Not Possible.'; }
24 |
25 | numArr[switchLeft[0]] = lastNum[1];
26 | numArr[lastNum[0]] = switchLeft[1];
27 |
28 | return sortRemainingNumbers(numArr, switchLeft[0]);
29 | }
30 |
31 | console.log('------------------------------');
32 | console.log('Input into nextNum: ', '12345');
33 | console.log('The result: ', nextNum('12345'));
34 | console.log('The answer should be: ', '12354');
35 | console.log('------------------------------');
36 | console.log('Input into nextNum: ', '54321');
37 | console.log('The result: ', nextNum('54321'));
38 | console.log('The answer should be: ', 'Should not be possible');
39 | console.log('------------------------------');
40 | console.log('Input into nextNum: ', '981543');
41 | console.log('The result: ', nextNum('981543'));
42 | console.log('The answer should be: ', '983145');
43 | console.log('------------------------------');
44 | console.log('Input into nextNum: ', '4011122');
45 | console.log('The result: ', nextNum('4011122'));
46 | console.log('The answer should be: ', '4011212');
47 | console.log('------------------------------');
48 | console.log('Input into nextNum: ', '122222222222222');
49 | console.log('The result: ', nextNum('122222222222222'));
50 | console.log('The answer should be: ', '222222222222222');
51 | console.log('———————————————');
52 |
--------------------------------------------------------------------------------
/problems/prob43/longest_palindrome.js:
--------------------------------------------------------------------------------
1 | // *** define functions *** //
2 |
3 | function getPalindromes(str, result) {
4 | // compare substrings
5 | for (var i = 0; i < str.length; i++) {
6 | // compare one left
7 | if (str[i] === str[i - 1]) {
8 | result = analyzePalindrome(str[i] + str[i - 1], str, i - 1, i);
9 | // compare one right
10 | } else if (str[i] === str[i + 2]) {
11 | result = analyzePalindrome(str[i] + str[i + 1], str, i, i + 1);
12 | // compare one left AND one right
13 | } else if (str[i - 1] === str[i + 1]) {
14 | result = analyzePalindrome(str[i - 1] + str[i] + str[i + 1], str, i - 1, i + 1);
15 | }
16 | }
17 | return result;
18 | }
19 |
20 | var analyzePalindrome = function (currentResult, str, leftIndex, rightIndex) {
21 | while ((str[leftIndex - 1] === str[rightIndex + 1]) && (currentResult !== str)) {
22 | currentResult = str[leftIndex -= 1] + currentResult + str[rightIndex += 1];
23 | }
24 | if (currentResult.length > result.length) {
25 | result = currentResult;
26 | }
27 | return result;
28 | };
29 |
30 |
31 | // *** invoke functions *** //
32 |
33 | var result = '';
34 | var str = 'I am a dazzled racecar driver';
35 | console.log(getLongestPalindrome(str, result) === 'd racecar d');
36 | var result = '';
37 | var str2 = 'wow racecar wow';
38 | console.log(getLongestPalindrome(str2, result) === 'wow racecar wow');
39 |
--------------------------------------------------------------------------------
/problems/prob43/longest_palindrome_brute.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Brute force (no whitespace):
4 |
5 | sample string => "d racecar anna"
6 |
7 | 1. Split string into an array of strings => ['d', 'racecar' 'anna']
8 | 2. Loop through the array of strings, find if specific string is a
9 | palindrome; and, if so, push it into an array (using 'filter()')
10 | => ['racecar' 'anna']
11 | 3. Find longest string (using `reduce()`) => ['racecar']
12 |
13 | How do you handle whitespace? :(
14 |
15 | */
16 |
17 | // helpers
18 | function splitString(str) {
19 | return str.split(' ');
20 | }
21 |
22 | function getPalindromes(arr) {
23 | return arr.filter(function(str) {
24 | return str === splitString(str).reverse().join('');
25 | });
26 | }
27 |
28 | // main
29 | function getLongestPalindrome(str) {
30 | strArray = splitString(str);
31 | palindromeArr = getPalindromes(strArray);
32 | return palindromeArr.reduce(function (previous, current) {
33 | return current.length > previous.length ? current : previous;
34 | }, '');
35 | }
36 |
37 | console.log(getLongestPalindrome("d racecar anna") === "racecar");
38 |
--------------------------------------------------------------------------------
/problems/prob44/byte-string.js:
--------------------------------------------------------------------------------
1 | var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
2 |
3 | function byteString(value) {
4 |
5 | var i;
6 |
7 | for (i = 0; value >= 1024 && i < 8; i++) {
8 | value /= 1024;
9 | }
10 |
11 | return value.toFixed(2) + ' ' + units[i];
12 | }
13 |
14 | module.exports = byteString;
15 |
16 |
17 | // var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
18 |
19 | // function byteString(value) {
20 | // var factor = Math.pow(10, 2);
21 | // // var getUnit = ??????
22 | // var output = Math.ceil(value / Math.pow(1024, 2) * factor) / factor;
23 |
24 | // return num.toFixed(2) + ' ' + getUnit;
25 | // }
26 |
--------------------------------------------------------------------------------
/problems/prob44/my-solution-byte-string-spec.js:
--------------------------------------------------------------------------------
1 | var byteString = require('./byte-string.js');
2 |
3 | describe('Byte String', function() {
4 | it('should show B format', function() {
5 | expect(byteString(1022)).toBe('1022.00 B');
6 | });
7 |
8 | it('should show KB format', function() {
9 | expect(byteString(10221)).toBe('9.98 KB');
10 | });
11 |
12 | it('should show MB format', function() {
13 | expect(byteString(1022932324)).toBe('975.54 MB');
14 | });
15 |
16 | it('should show GB format', function() {
17 | expect(byteString(1022932123237)).toBe('952.68 GB');
18 | });
19 |
20 | it('should show TB format', function() {
21 | expect(byteString(1022932453333234)).toBe('930.35 TB');
22 | });
23 |
24 | it('should show PB format', function() {
25 | expect(byteString(1022932453333234444)).toBe('908.55 PB');
26 | });
27 |
28 | it('should show EB format', function() {
29 | expect(byteString(1022932453333234444324)).toBe('887.25 EB');
30 | });
31 |
32 | it('should show ZB format', function() {
33 | expect(byteString(1022932453333234444324454)).toBe('866.46 ZB');
34 | });
35 |
36 | it('should show YB format', function() {
37 | expect(byteString(10243245333323444432445431)).toBe('8.47 YB');
38 | });
39 |
40 | it('should show YB format when number larger than 1024YB', function() {
41 | var result = byteString(232932453333234444324454333424324);
42 | expect(result).toBe('192677209.43 YB');
43 | });
44 |
45 | });
46 |
--------------------------------------------------------------------------------
/problems/prob44/my-solution-byte-string.js:
--------------------------------------------------------------------------------
1 | var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
2 |
3 | module.exports = function byteString(value) {
4 |
5 | var i;
6 |
7 | while (i = 0, value >= 1024 && i < 8, i++) {
8 | value /= 1024;
9 | }
10 |
11 | return value.toFixed(2) + ' ' + units[i];
12 |
13 | };
14 |
15 |
16 |
--------------------------------------------------------------------------------
/problems/prob44/test-byte-string.js:
--------------------------------------------------------------------------------
1 | var expect = require('chai').expect;
2 | var byteString = require('./byte-string.js');
3 |
4 |
5 | describe('Byte String', function() {
6 | it('should show B format', function() {
7 | expect(byteString(1022)).to.equal('1022.00 B');
8 | });
9 |
10 | it('should show KB format', function() {
11 | expect(byteString(10221)).to.equal('9.98 KB');
12 | });
13 |
14 | it('should show MB format', function() {
15 | expect(byteString(1022932324)).to.equal('975.54 MB');
16 | });
17 |
18 | it('should show GB format', function() {
19 | expect(byteString(1022932123237)).to.equal('952.68 GB');
20 | });
21 |
22 | it('should show TB format', function() {
23 | expect(byteString(1022932453333234)).to.equal('930.35 TB');
24 | });
25 |
26 | it('should show PB format', function() {
27 | expect(byteString(1022932453333234444)).to.equal('908.55 PB');
28 | });
29 |
30 | it('should show EB format', function() {
31 | expect(byteString(1022932453333234444324)).to.equal('887.25 EB');
32 | });
33 |
34 | it('should show ZB format', function() {
35 | expect(byteString(1022932453333234444324454)).to.equal('866.46 ZB');
36 | });
37 |
38 | it('should show YB format', function() {
39 | expect(byteString(10243245333323444432445431)).to.equal('8.47 YB');
40 | });
41 |
42 | it('should show YB format when number larger than 1024YB', function() {
43 | var result = byteString(232932453333234444324454333424324);
44 | expect(result).to.equal('192677209.43 YB');
45 | });
46 |
47 | });
48 |
--------------------------------------------------------------------------------
/problems/prob45/csv_parse.js:
--------------------------------------------------------------------------------
1 | function csvParse(inputString) {
2 | var outputArray = [];
3 | inputArray = inputString.split(',');
4 | for (var i = 0; i < inputArray.length; i++) {
5 | if (!Number.isNaN(+inputArray[i])) {
6 | outputArray.push(+inputArray[i]);
7 | } else {
8 | outputArray.push(inputArray[i].replace(/['"]+/g, '').trim());
9 | }
10 | }
11 | return outputArray;
12 | }
13 |
14 | module.exports = csvParse;
15 |
--------------------------------------------------------------------------------
/problems/prob45/test-csv-parse.js:
--------------------------------------------------------------------------------
1 | var expect = require('chai').expect;
2 | var csvParse = require('./csv_parse.js');
3 |
4 |
5 | describe('CSV Parse', function() {
6 | it('should parse a string of integers correctly', function() {
7 | var input = '3,7,9,1,25';
8 | var output = [ 3, 7, 9, 1, 25 ];
9 | expect(csvParse(input)).to.deep.equal(output);
10 | });
11 | it('should parse a string of strings correctly', function() {
12 | var input = '"3","7","9","1","25"';
13 | var output = ["3", "7", "9", "1", "25"];
14 | expect(csvParse(input)).to.deep.equal(output);
15 | });
16 | it('should parse a string of integers and strings correctly', function() {
17 | var input = '1, "one", 2, "two", 3, "three"';
18 | var output = [1, "one", 2, "two", 3, "three"];
19 | expect(csvParse(input)).to.deep.equal(output);
20 | });
21 | });
22 |
--------------------------------------------------------------------------------
/problems/prob46/vowels.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Create a function that takes a word as an argument and returns true if and only if all of the vowels in the word are the same.
4 | - myFn('oligopoly') => false
5 | - myFn('zoom') => true
6 |
7 | 1. Break apart word into an array of letters
8 | 2. Determine if each letter is a vowel
9 | - If so, add the letter to an array
10 | 3. Check to see if all letters in the vowel array are the same
11 |
12 | */
13 |
14 |
15 | // ** Globals **//
16 |
17 | var vowels = ['a', 'e', 'i', 'o', 'u', 'y'];
18 |
19 |
20 | // ** Controller ** //
21 |
22 | function compareVowels (str) {
23 | var strLower = toLower(str);
24 | var splitArray = splitString(strLower);
25 | var vowelArray = vowelParse(splitArray);
26 | var clone = vowelArray.slice(0);
27 | var solution = vowelCompare(vowelArray, clone);
28 | return solution;
29 | }
30 |
31 | console.log(compareVowels("Oligopoly"));
32 | console.log(compareVowels("Bzz"));
33 | console.log(compareVowels("Zoom"));
34 |
35 |
36 | // ** Helper Functions ** //
37 |
38 | function splitString(str) {
39 | return str.split('');
40 | }
41 |
42 | function toLower(str) {
43 | return str.toLowerCase();
44 | }
45 |
46 | function vowelParse(array) {
47 | var vowelArray = [];
48 | for (i = 0; i < array.length; i++) {
49 | for (j = 0; j < vowels.length; j++) {
50 | if (array[i] === vowels[j]) {
51 | vowelArray.push(array[i]);
52 | }
53 | }
54 | }
55 | return vowelArray;
56 | }
57 |
58 | function vowelCompare(array1, array2) {
59 | if (!array1.length) {
60 | return false;
61 | } else {
62 | for (i = 1; i < array1.length; i++) {
63 | for (j = 0; j <= array2.length; j++) {
64 | if (array1[i] === array2[j]) {
65 | return true;
66 | } else {
67 | return false;
68 | }
69 | }
70 | }
71 | }
72 | }
--------------------------------------------------------------------------------
/problems/prob47/main.js:
--------------------------------------------------------------------------------
1 | var flattenArray = require('./util.js');
2 |
3 | var nestedArray = [
4 | [1, 2, 3],
5 | [4, 5, 6],
6 | [7, 8, 9]
7 | ];
8 |
9 | var results = flattenArray(nestedArray, function(err, data){
10 | if (err) {
11 | return err;
12 | } else {
13 | return data;
14 | }
15 | });
16 |
17 | console.log(results);
--------------------------------------------------------------------------------
/problems/prob47/util.js:
--------------------------------------------------------------------------------
1 | function flattenArray(arr, callback) {
2 | if (!Array.isArray(arr)) {
3 | return callback('Please use an array!');
4 | } else {
5 | var singleArray = [].concat.apply([], arr);
6 | return callback(null, singleArray);
7 | }
8 | }
9 |
10 | module.exports = flattenArray;
11 |
12 |
--------------------------------------------------------------------------------
/problems/prob48/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/problems/prob48/main.js:
--------------------------------------------------------------------------------
1 | function intersection(arr1, arr2) {
2 | var newArr = [];
3 | for(var i = 0; i < arr1.length; i++) {
4 | for(var j = 0; j < arr2.length; j++) {
5 | if (arr1[i] === arr2[j]) {
6 | newArr.push(arr1[i]);
7 | }
8 | }
9 | }
10 | return newArr;
11 | }
--------------------------------------------------------------------------------
/problems/prob48/test.js:
--------------------------------------------------------------------------------
1 | var expect = chai.expect;
2 |
3 | describe('Intersection', function() {
4 | it('intersection([1,2,3], [1,3,5]) should return [1,3]', function() {
5 | expect(intersection([1,2,3], [1,3,5])).to.deep.equal([1,3]);
6 | });
7 | it('intersection([2,4,6], [4,6,8]) should return [4,6]', function() {
8 | expect(intersection([2,4,6], [4,6,8])).to.deep.equal([4,6]);
9 | });
10 | });
--------------------------------------------------------------------------------
/problems/prob49/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/problems/prob49/main.js:
--------------------------------------------------------------------------------
1 | function countIt(str) {
2 | // remove blank space
3 | var formattedString = str.replace(/\s/g, '');
4 | // convert to lowercase
5 | var lowerCaseString = formattedString.toLowerCase();
6 | // convert to array
7 | var wordArray = lowerCaseString.split('');
8 | // create container
9 | var results = {};
10 | // loop thrrough array
11 | for (var i = 0; i < wordArray.length; i++) {
12 | // make sure the element is a letter
13 | if ( wordArray[i] >= 'a' && wordArray[i] <= 'z' ) {
14 | // check if letter is a key
15 | if (wordArray[i] in results) {
16 | // increment if key
17 | results[wordArray[i]] += 1;
18 | } else {
19 | // add if not key
20 | results[wordArray[i]] = 1;
21 | }
22 | }
23 | }
24 | console.log(results)
25 | // return the results
26 | return results;
27 | }
--------------------------------------------------------------------------------
/problems/prob49/test.js:
--------------------------------------------------------------------------------
1 | var expect = chai.expect;
2 |
3 | describe('countIt()', function() {
4 | it('countIt(\'Hello World\') should return [1,3]', function() {
5 | expect(countIt('Hello World')).to.deep.equal({'d': 1,'e': 1,'h': 1,'l': 3,'o': 2,'r': 1,'w': 1});
6 | });
7 | it('countIt(\'The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.\') should return [1,3]', function() {
8 | expect(countIt('The quick brown fox jumps over the lazy dog and the sleeping cat early in the day.')).to.deep.equal({'a': 5,'b': 1,'c': 2,'d': 3,'e': 8,'f': 1,'g': 2,'h': 4,'i': 3,'j': 1,'k': 1,'l': 3,'m': 1,'n': 4,'o': 4,'p': 2,'q': 1,'r': 3,'s': 2,'t': 5,'u': 2,'v': 1,'w': 1,'x': 1,'y': 3,'z': 1});
9 | });
10 | });
--------------------------------------------------------------------------------
/problems/prob50/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/problems/prob50/main.js:
--------------------------------------------------------------------------------
1 | // function checkRamp(num) {
2 | // // convert number to string then create an array
3 | // var numberArray = num.toString().split('');
4 | // // loop through the array
5 | // for (var i = 0; i < numberArray.length; i++) {
6 | // // check to see if the current number is less than
7 | // // or equal two the next number
8 | // if (parseInt(numberArray[i]) <= parseInt(numberArray[i+1])) {
9 | // // if true
10 | // return true;
11 | // } else {
12 | // // if false
13 | // return false;
14 | // }
15 | // }
16 | // }
17 |
18 |
19 | // function checkRamp(num) {
20 | // // convert number to string
21 | // numString = num.toString();
22 | // // loop until end of string
23 | // // why start at 1?
24 | // for (var i = 1; i < numString.length; i++) {
25 | // // check to see if the previous number is
26 | // // greater than the current number
27 | // if (numString[i - 1] > numString[i]) {
28 | // // if false
29 | // return false;
30 | // }
31 | // }
32 | // // is a valid ramp number!
33 | // return true;
34 | // }
35 |
36 | /*
37 |
38 | convert number to string
39 | loop (0 to length of string)
40 | check if prev num is greater than current num
41 | if yes - return false
42 | if no - return true
43 |
44 | */
45 |
46 | function checkRamp(num) {
47 | var numStr = num.toString();
48 | for (var i = 1; i < numStr.length; i++) {
49 | if (numStr[i] < numStr[i-1]) {
50 | return false;
51 | // break;
52 | }
53 | }
54 | return true;
55 | // break
56 | }
57 |
58 | /*
59 |
60 | convert number to string
61 | sort
62 | check if original is the same as sorted
63 | if yes - return true
64 | if no - return false
65 |
66 | */
67 |
68 | // function checkRamp(num) {
69 | // if(num === num.sort(){
70 | // return true
71 | // })
72 |
73 | // }
74 |
75 | /*
76 |
77 | original sorted
78 | 1. 1234 1234
79 | 2. 1324 1234
80 | 3. 1111 1111
81 | 4. 0000 0000
82 | 5. 1230 0123
83 |
84 | */
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
--------------------------------------------------------------------------------
/problems/prob50/test.js:
--------------------------------------------------------------------------------
1 | var expect = chai.expect;
2 |
3 | describe('checkRamp()', function() {
4 | it('checkRamp(1234) should return true', function() {
5 | expect(checkRamp(1234)).to.equal(true);
6 | });
7 | it('checkRamp(1032) should return true', function() {
8 | expect(checkRamp(1032)).to.equal(false);
9 | });
10 | it('checkRamp(1124) should return true', function() {
11 | expect(checkRamp(1124)).to.equal(true);
12 | });
13 | });
--------------------------------------------------------------------------------
/problems/prob51/main.js:
--------------------------------------------------------------------------------
1 | //** definitions **//
2 |
3 | function isPalindrome(input) {
4 | // sanitize string
5 | var sanitizeString = sanitize(input);
6 | return sanitizeString === reverseString(sanitizeString);
7 | }
8 |
9 | function sanitize(str) {
10 | return str.toLowerCase().replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,'').replace(/\s/g, '');
11 | }
12 |
13 | function reverseString(str) {
14 | return str.split('').reverse().join('');
15 | }
16 |
17 |
18 | //** calls **//
19 |
20 | console.log(isPalindrome('rAceCar'));
21 | console.log(isPalindrome('anna'));
22 | console.log(isPalindrome('banana'));
23 | console.log(isPalindrome('I, man, am regal - a German am I'));
24 | console.log(isPalindrome('No lemons, no melon'));
25 | console.log(isPalindrome('Was it a car or a cat I saw?'));
26 | console.log(isPalindrome('Probably not a palindrome'));
--------------------------------------------------------------------------------
/problems/prob52/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/problems/prob52/main.js:
--------------------------------------------------------------------------------
1 | // non-destructive
2 | // alters the inputs/arguments/state
3 | function combineAndSort(array1, array2) {
4 | var newArray = array1.slice();
5 | array2.forEach(function(el) {
6 | newArray.push(el);
7 | });
8 | return newArray.sort();
9 | }
10 |
11 |
12 |
13 | // // destructive
14 | // function combineAndSort(array1, array2) {
15 | // var newArray = array1.splice();
16 | // array2.forEach(function(el) {
17 | // newArray.push(el);
18 | // });
19 | // return newArray.sort();
20 | // }
21 | //
22 | // function combineAndSort(array1, array2) {
23 | // array2.forEach(function(el) {
24 | // array1.push(el);
25 | // });
26 | // return array1.sort();
27 | // }
28 |
--------------------------------------------------------------------------------
/problems/prob52/test.js:
--------------------------------------------------------------------------------
1 | (function() {
2 |
3 | 'use strict';
4 |
5 | var expect = chai.expect;
6 |
7 | describe('combineAndSort()', function() {
8 |
9 | var array1 = ['cat', 'dog', 'fish', 'zebra'];
10 | var array2 = ['lion', 'aardvark', 'gorilla'];
11 | var combined = ['aardvark', 'cat', 'dog', 'fish', 'gorilla', 'lion', 'zebra'];
12 |
13 | it('combineAndSort(array1, array2) should return a new array with all items in alphabetical order', function() {
14 | expect(combineAndSort(array1, array2)).to.eql(combined);
15 | });
16 |
17 | it('combineAndSort(array1, array2) should be non-destructive', function() {
18 | combineAndSort(array1, array2);
19 | expect(array1).to.eql(['cat', 'dog', 'fish', 'zebra']);
20 | expect(array2).to.eql(['lion', 'aardvark', 'gorilla']);
21 |
22 | });
23 |
24 | });
25 |
26 | }());
27 |
--------------------------------------------------------------------------------
/problems/prob53/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/problems/prob53/main.js:
--------------------------------------------------------------------------------
1 | // brute force
2 |
3 | /*
4 |
5 | 1- convert number to array of strings
6 | 1- iterate through array
7 | 2- multiply each grouping of 5 numbers (in order)
8 | 3- add product to an array
9 | 4- find largest value in array
10 |
11 | */
12 |
13 | function productOfFiveOne(num) {
14 | var productArray = [];
15 | var largestValue = -Infinity;
16 | var numberArray = num.toString().split(''); // 1
17 | for (var i = 0; i < numberArray.length; i++) { // 2
18 | var product = ( // 3
19 | parseInt(numberArray[i]) *
20 | parseInt(numberArray[i + 1]) *
21 | parseInt(numberArray[i + 2]) *
22 | parseInt(numberArray[i + 3]) *
23 | parseInt(numberArray[i + 4])
24 | );
25 | if (!isNaN(product)) {
26 | productArray.push(product); // 4
27 | }
28 | }
29 | for (var j = 0; j < productArray.length; j++) { // 5
30 | if (productArray[j] > largestValue) {
31 | largestValue = productArray[j];
32 | }
33 | }
34 | return largestValue;
35 | }
36 |
37 | console.log('brute force 1:');
38 |
39 | console.log(productOfFiveOne(111333321));
40 | console.log(productOfFiveOne(155555));
41 | console.log(productOfFiveOne(127289373913828309127381263));
42 |
43 | // brute force take 2
44 |
45 | /*
46 |
47 | 1- convert number to array
48 | 1- iterate through array
49 | 2- multiply each grouping of 5 numbers (in order)
50 | 3- add product to an array
51 | 4- find largest value in array as a seperate function
52 |
53 | */
54 |
55 | function productOfFiveTwo(num) {
56 | var productArray = [];
57 | var numberArray = num.toString().split(''); // 1
58 | for (var i = 0; i < numberArray.length; i++) { // 2
59 | var product = ( // 3
60 | parseInt(numberArray[i]) *
61 | parseInt(numberArray[i + 1]) *
62 | parseInt(numberArray[i + 2]) *
63 | parseInt(numberArray[i + 3]) *
64 | parseInt(numberArray[i + 4])
65 | );
66 | if (!isNaN(product)) {
67 | productArray.push(product); // 4
68 | }
69 | }
70 | return getLargestValueFromAnArray(productArray);
71 | }
72 |
73 | function getLargestValueFromAnArray(arr) {
74 | var largestValue = -Infinity;
75 | for (var i = 0; i < arr.length; i++) { // 5
76 | if (arr[i] > largestValue) {
77 | largestValue = arr[i];
78 | }
79 | }
80 | return largestValue;
81 | }
82 |
83 | console.log('');
84 | console.log('brute force 2:');
85 |
86 | console.log(productOfFiveTwo(111333321));
87 | console.log(productOfFiveTwo(155555));
88 | console.log(productOfFiveTwo(127289373913828309127381263));
89 |
90 | // brute force take 3
91 |
92 | /*
93 |
94 | 1- convert number to array
95 | 1- iterate through array with a hof
96 | 2- multiply each grouping of 5 numbers (in order)
97 | 3- add product to an array
98 | 4- find largest value in array as a seperate function
99 |
100 | */
101 |
102 | function productOfFiveThree(num) {
103 | var numberArray = num.toString().split(''); // 1
104 | var productArray = numberArray.map(function(num, index, arr) {
105 | var product = ( // 3
106 | parseInt(num) *
107 | parseInt(arr[index + 1]) *
108 | parseInt(arr[index + 2]) *
109 | parseInt(arr[index + 3]) *
110 | parseInt(arr[index + 4])
111 | );
112 | if (!isNaN(product)) {
113 | return product; // 4
114 | }
115 | });
116 | return getLargestValueFromAnArray(productArray);
117 | }
118 |
119 | function getLargestValueFromAnArray(arr) {
120 | var largestValue = -Infinity;
121 | for (var i = 0; i < arr.length; i++) { // 5
122 | if (arr[i] > largestValue) {
123 | largestValue = arr[i];
124 | }
125 | }
126 | return largestValue;
127 | }
128 |
129 | console.log('');
130 | console.log('brute force 3:');
131 |
132 | console.log(productOfFiveThree(111333321));
133 | console.log(productOfFiveThree(155555));
134 | console.log(productOfFiveThree(127289373913828309127381263));
135 |
--------------------------------------------------------------------------------
/problems/prob53/test.js:
--------------------------------------------------------------------------------
1 | (function() {
2 |
3 | 'use strict';
4 |
5 | }());
6 |
--------------------------------------------------------------------------------
/problems/prob54/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/problems/prob54/main.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Write a function named `rotateMatrix()` that rectangular array of numbers (a matrix) and returns the matrix rotated 90 degrees to the right.
4 |
5 | 1. Do you understand the problem?
6 | - Yes: Talk it out with the interviewer, making sure you understand what is expected
7 | - No: clarify the problem, ask "what ifs", clarify inputs and outputs, ask for more samples, think of hypotheticals
8 | - Still no: Try something a bit easier, how do you break this problem down ("I have no idea where to start, but I know how to write a loop - so I am going to start there")
9 | 2. Write psuedocode
10 | - Clarify that you are going in the right direction
11 | 3. Write sandwich code
12 | 4. Wite code
13 | 5. Test - manually test, automate those tests
14 | 6. Burn it down, refactor, do it again, test, burn it down, refactor
15 |
16 | */
17 |
18 | // brute force
19 | function rotateMatrix(matrix) {
20 | let newArray = [];
21 | let result = [];
22 | for (let i = 0; i < matrix[0].length; i++) {
23 | newArray = [];
24 | for (let j = 0; j < matrix.length; j++) {
25 | if (matrix[j]) {
26 | newArray.unshift(matrix[j][i]);
27 | }
28 | }
29 | result.push(newArray);
30 | }
31 | return result;
32 | }
33 |
34 | // function rotateMatrix(matrix) {
35 | // return matrix[0].map((col, i) => {
36 | // return matrix.map((row, j) => {
37 | // let neg = matrix.length - (j + 1);
38 | // return matrix[neg][i];
39 | // });
40 | // });
41 | // }
42 |
43 | const matrix1 = [
44 | [44, 23],
45 | [21, 10],
46 | [9, 28],
47 | [85, 16],
48 | [33, 18]
49 | ];
50 |
51 | const matrix1Expected = [ [33, 85, 9, 21, 44], [18, 16, 28, 10, 23] ];
52 |
53 | console.log(rotateMatrix(matrix1));
54 | console.log('Expected: ', matrix1Expected);
55 |
56 | const matrix2 = [
57 | [29,62,8],
58 | [12,60, 31],
59 | [99,79,12]
60 | ];
61 |
62 | const matrix2Expected = [
63 | [99, 12, 29],
64 | [79, 60, 62],
65 | [12, 31, 8]
66 | ];
67 |
68 | console.log('\n', rotateMatrix(matrix2));
69 | console.log('Expected: ', matrix2Expected);
70 |
--------------------------------------------------------------------------------
/problems/prob54/test.js:
--------------------------------------------------------------------------------
1 | (function() {
2 |
3 | 'use strict';
4 |
5 | }());
6 |
--------------------------------------------------------------------------------
/problems/prob55/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/problems/prob55/main.js:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Write a function `weirdWords()` that takes a string and changes every letter to the next letter in the alphabet and then returns the result. Note: spaces and special characters should remain the same. Capital letters should remain capitalized.
4 | - Input: `What is your name?`
5 | - Output: `Xibu jt zpvs obnf?`
6 |
7 | */
8 |
9 | function weirdWords(str) {
10 | const stringArray = str.split('');
11 | const result = stringArray.map((letter) => {
12 | return getNextCharacter(letter);
13 | });
14 | return result.join('');
15 | }
16 |
17 | function getNextCharacter(char) {
18 | var newCode;
19 | // is character a word character?
20 | if(/\w/.test(char)) {
21 | // get an integer representing the string
22 | const currentCode = char.charCodeAt(0);
23 | // is the letter a 'z'?
24 | if(currentCode % 32 === 26) {
25 | // yes? go back to the begining
26 | newCode = currentCode - 25;
27 | } else {
28 | // no? go forward 1
29 | newCode = currentCode + 1;
30 | }
31 | char = String.fromCodePoint(newCode);
32 | }
33 | return char;
34 | }
35 |
36 | // console.log(weirdWords('What is your name?'));
37 |
38 | // const weirdWords = (str) => {
39 | // // split string into an array, iterating through the new array
40 | // return str.split('').map(el => {
41 | // // el.charCodeAt(0) => converts character to the utf-16 integer
42 | // const getCharCode = el.charCodeAt(0)
43 | // // test if this code is valid -> http://stackoverflow.com/a/9539389/1799408
44 | // if (getCharCode > 64 && getCharCode < 122 )
45 | // // el.charCodeAt(0) + 1 => increment integer
46 | // // convert back to regular character
47 | // return String.fromCodePoint(el.charCodeAt(0) + 1);
48 | // // is the code a "z" return 'a'
49 | // else if (getCharCode === 123) {
50 | // return 'a';
51 | // } else {}
52 | // return el;
53 | // }).join('')
54 | // }
55 | //
56 | // console.log(weirdWords('What is your name?'))
57 |
--------------------------------------------------------------------------------
/problems/prob55/test.js:
--------------------------------------------------------------------------------
1 | (function() {
2 |
3 | 'use strict';
4 |
5 | const expect = chai.expect;
6 |
7 | // integration
8 |
9 | describe('weirdWords()', () => {
10 | it('should return a string where every letter in the given string is the next letter in the alphabet', () => {
11 | const basicTest = weirdWords('a');
12 | expect(basicTest).to.eql('b');
13 | const firstTest = weirdWords('What is your name?');
14 | expect(firstTest).to.eql('Xibu jt zpvs obnf?');
15 | const secondTest = weirdWords('z');
16 | expect(secondTest).to.eql('a');
17 | const thirdTest = weirdWords('Z');
18 | expect(thirdTest).to.eql('A');
19 | });
20 |
21 | });
22 |
23 | }());
24 |
--------------------------------------------------------------------------------
/problems/prob56/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Mocha Tests
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/problems/prob56/main.js:
--------------------------------------------------------------------------------
1 | function twoSum(numbers, target) {
2 | for(let i = 0; i < numbers.length; i++) {
3 | for(let j = 1; j < numbers.length; j++) {
4 | if(numbers[i] + numbers[j] === target) {
5 | return [i , j];
6 | }
7 | }
8 | }
9 | return false;
10 | }
11 |
12 | console.log(twoSum([1, 2, 3, 4, 5, 6, 7], 13));
13 |
--------------------------------------------------------------------------------
/problems/prob56/test.js:
--------------------------------------------------------------------------------
1 | (function() {
2 |
3 | 'use strict';
4 |
5 | const expect = chai.expect;
6 |
7 | describe('foo', () => {
8 | it('should always be followed by bar', () => {
9 | expect(1 + 1).to.eql(2);
10 | });
11 | });
12 |
13 | }());
14 |
--------------------------------------------------------------------------------