Skip to content

Instantly share code, notes, and snippets.

@diklein
Last active October 1, 2016 01:07
Show Gist options
  • Save diklein/ca98dcaf83484040749b14ffc53b1d77 to your computer and use it in GitHub Desktop.
Save diklein/ca98dcaf83484040749b14ffc53b1d77 to your computer and use it in GitHub Desktop.
Javascript — Week 2
// 1. What's the max number?
var max = 0;
for (var i = 0; i < a.length; i++) {
if(a[i] > max) {
max = a[i];
}
}
console.log("max number is " + max);
// 2. What's the sum of all the numbers?
var sum = 0;
for (var i = 0; i < a.length; i++) {
sum = sum + a[i];
}
console.log("sum: " + sum);
// 3. Which numbers are between 50 and 100?
var numbers = [];
for (var i = 0; i < a.length; i++) {
if (a[i] > 50 && a[i] < 100) {
numbers.push(a[i]);
}
}
console.log("numbers between 50 and 100: " + numbers);
// 4. How many numbers greater than 500?
var greaterThan500 = 0;
for (var i = 0; i < a.length; i++) {
if (a[i] > 500) {
greaterThan500++;
}
}
console.log("numbers greater than 500: " + greaterThan500);
// 5. How many even numbers?
var even = [];
for (var i = 0; i < a.length; i++) {
if ((a[i] % 2) == 0) {
even.push(a[i]);
}
}
console.log("even numbers: " + even.length);
// 6. How many odd numbers?
var odd = 0;
for (var i = 0; i < a.length; i++) {
if ((a[i] % 2) == 1) {
odd++;
}
}
console.log("odd numbers: " + odd);
// 7. What's the largest even number?
var maxEven = 0;
for (var i = 0; i < a.length; i++) {
if ((a[i] % 2) == 0) {
if(a[i] > maxEven) {
maxEven = a[i];
}
}
}
console.log("max even is " + maxEven);
// 8. How many numbers, whose sum of digits is greater than 10?
// Solution 1
var breakApart;
var greaterThan10 = 0;
for (var i = 0; i < a.length; i++) {
breakApart = a[i].toString()
breakApart = breakApart.split("");
var sumOfValue = 0;
for (var j = 0; j < breakApart.length; j++) {
sumOfValue += parseInt(breakApart[j]);
}
if (sumOfValue > 10) {
greaterThan10++;
}
}
console.log("greater than 50: " + greaterThan10);
// Solution 2
a.forEach(findSum);
function findSum(item) {
var digits = item.toString();
digits = digits.split("");
var sumOfDigits = 0;
digits.forEach(addDigits);
function addDigits(item) {
sumOfDigits = sumOfDigits + parseInt(item);
}
if (sumOfDigits > 10) {
greaterThan10++;
}
}
console.log("greater than 50: " + greaterThan10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment