Code Challenge: Additive Persistence

Each week, I offer up a JavaScript code challenge. Want more? You can find others here.

First, I’ll admit that I’m a day overdue on this code challenge. Last week, I was on vacation in Austin, TX, and I’m still playing catchup. Still, that’s no excuse! After being away for a week, I felt a bit rusty. Today’s code challenge is a shorter one from Coderbyte.

Using the JavaScript language, have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit. For example: if num is2718 then your program should return 2 because 2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9.

Here’s my solution collapsed:

function AdditivePersistence(num) {
    // Break up the numbers into an array
    var numbers = num.toString().split('');
    // Set the initial count to 0
    var count = 0;

    // Return the count if num is a single number
    if (numbers.length <= 1) {
        return count;
    };

    // If num isn't a single number
    do {
        // Set the initial sum to 0
        var sum = 0;
        // Loop over the numbers array and add each number to the sum
        for (var i = 0; i<numbers.length; i++) {
            sum = sum + Number(numbers[i]);
        }
        // Set numbers equal to the new array after splitting the sum
        numbers = sum.toString().split('');
        // Increment the count variable
        count = count + 1;
    // Do this while numbers.length is larger than 1
    } while (numbers.length > 1);

    return count;
};

First, I took the num argument passed in and split it up into an array so I could cycle over it. If the array had a length of 1, I could just return 0.

If the length of the array was larger than 1, I started a do/while loop. I cycled over each number in the array with a for loop and added it to the sum variable. At the end of the for loop, I set the numbers variable equal to the sum broken up into an array. For example, if the initial number was 2345, the sum would be 14. So, the numbers variable would be set equal to [1,4]. I repeated this process while numbers.length was greater than 1. Finally, I returned the count, which was incremented each time I went through the do/while loop.

Code Challenge: Number Search

Each week, I offer up a JavaScript code challenge. Want more? You can find others here.

This week’s code challenge again comes from Coderbyte. It’s quite a bit easier and shorter than last week mainly because I was slammed with Drink for Pink events and prepping for the Automattic Grand Meetup!

Here’s the gist:

Using the JavaScript language, have the function NumberSearch(str) take the str parameter, search for all the numbers in the string, add them together, then return that final number divided by the total amount of letters in the string. For example: if str is “Hello6 9World 2, Nic8e D7ay!” the output should be 2. First if you add up all the numbers, 6 + 9 + 2 + 8 + 7 you get 32. Then there are 17 letters in the string. 32 / 17 = 1.882, and the final answer should be rounded to the nearest whole number, so the answer is 2. Only single digit numbers separated by spaces will be used throughout the whole string (So this won’t ever be the case: hello44444 world). Each string will also have at least one letter.

Here’s a test case for example:

Input = “H3ello9-9”
Expected Output = 4

The string “H3ello9-9” contains 6 items that aren’t numbers. If you sum up the numbers (9,9,3), you’ll get 21. If you divide that by 6, you get 3.5, which rounds to 4.

Here’s another test case:

Input = “One Number1
Expected Output = 0

Here’s my solution collapsed:

function numberSearch(str) {
	var separatedString = str.split('');
	var letters = [];
	var numbers = [];
	var sum = 0;

	for (var i=0; i<str.length; i++) {
		var currentItem = separatedString[i];
		if (isNaN(parseInt(currentItem))) {
			letters.push(currentItem);
		} else {
			numbers.push(currentItem);
		};
	};

	for (var i=0; i<numbers.length; i++) {
		currentNumber = Number(numbers[i]);
		sum = sum + currentNumber;
	};

	return (Math.round(sum/letters.length));
};

First, we create some variables we’ll need later on. The first (separatedString) breaks up the given string. The variables letters and numbers hold empty arrays. Then, we set the sum to 0.

Next, we cycle over the string determining whether or not currentItem is a number by using isNaN(parseInt(currentItem)). If the item isn’t a number, push it on to the letters array. If it is a number, push it on to the numbers array.

Next, we cycle over the numbers array and add the currentNumber to the sum total.

Finally, we use the Math.round() method to round up the result of sum divided by letters.length and return that number.

Code Challenge: Blackjack

Each week, I offer up a JavaScript code challenge. Want more? You can find others here.

This week’s challenge comes from Coderbyte, which has been a fun resource. The instructions are a bit of a doozy:

Have the function BlackjackHighest(strArr) take the strArr parameter being passed which will be an array of numbers and letters representing blackjack cards. Numbers in the array will be written out. So for example strArr may be [“two”,”three”,”ace”,”king”]. The full list of possibilities for strArr is: two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace. Your program should output below, above, or blackjack signifying if you have blackjack (numbers add up to 21) or not and the highest card in your hand in relation to whether or not you have blackjack. If the array contains an ace but your hand will go above 21, you must count the ace as a 1. You must always try and stay below the 21 mark. So using the array mentioned above, the output should be below king. The ace is counted as a 1 in this example because if it wasn’t you would be above the 21 mark. Another example would be if strArr was [“four”,”ten”,”king”], the output here should be above king. If you have a tie between a ten and a face card in your hand, return the face card as the “highest card”. If you have multiple face cards, the order of importance is jack, queen, then king.

It sounds a bit confusing at first glance, but if you know how to play blackjack, the rules make sense, particularly the rules surrounding aces. Here are some test cases:

  • Input = “four”,”ace”,”ten”; Output = “below ten”
  • Input = “ace”,”queen”; Output = “blackjack ace”

Continue reading