The post Code Challenge: Simple Mode appeared first on Jeremey DuVall.

]]>Using the JavaScript language, have the function SimpleMode(arr) take the array of numbers stored in arr and return the number that appears most frequently (the mode). For example: if arr contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode return the one that appeared in the array first (ie. [5, 10, 10, 6, 5] should return 5 because it appeared first). If there is no mode return -1. The array will not be empty.

Here are some test cases:

Input = 5,5,2,2,1O Output = 5

Input = 3,4,1,6,10 Output = -1

Here’s my solution collapsed:

function SimpleMode(arr) { var highest = 1; var mostFrequently = -1; for ( var i = 0; i < arr.length; i++ ) { var count = 0; for ( var j = 0; j < arr.length; j++ ) { if ( arr[i] == arr[j] ) { count++; } } if ( count > highest ) { highest = count; mostFrequently = arr[i]; } } return mostFrequently; };

To start, I setup two variables. The variable `highest`

would hold the current highest frequency. For example, if the digit 2 appeared three times, `highest`

would be three. To start, I could safely set this to 1 since the array was promised not to be empty and a digit would have to appear once by default. The `mostFrequently`

variable held the actual digit that I wanted to return at the end (the one that appeared most frequently). Since I wanted to return -1 if there wasn’t a mode, I set `mostFrequently`

to -1 at the beginning.

Next, I started a for loop that would loop over the array. Within that for loop, I created another for loop comparing the item to every other item in the array. If the items matched, I incremented my counter variable.

for ( var i = 0; i < arr.length; i++ ) { var count = 0; for ( var j = 0; j < arr.length; j++ ) { if ( arr[i] == arr[j] ) { count++; } } }

Once the comparison for loop was finished, I compared the value of `count`

to the value of `highest`

. If it was greater, I replaced the value of `highest`

with `count`

and set the `mostFrequently`

variable to the current array item.

if ( count > highest ) { highest = count; mostFrequently = arr[i]; }

Solve it a different way? I want to hear it. Let me know in the comments!

The post Code Challenge: Simple Mode appeared first on Jeremey DuVall.

]]>The post Code Challenge: Greatest Common Factor appeared first on Jeremey DuVall.

]]>Using the JavaScript language, have the function Division(num1,num2) take both parameters being passed and return the Greatest Common Factor. That is, return the greatest number that evenly goes into both numbers with no remainder. For example: 12 and 16 both are divisible by 1, 2, and 4 so the output should be 4. The range for both parameters will be from 1 to 10^3.

Here are some test cases:

Input = 7 & num2 = 3 -> Output = 1

Input = 36 & num2 = 54 -> Output = 18

Here’s my solution collapsed:

function Division( num1, num2 ) { var gcf = 1; var higher = num2; var lower = num1; if ( num1 > num2 ) { higher = num1; lower = num2; }; for ( var i = 0; i < lower; i++ ) { if ( lower % i == 0 && higher % i == 0 && i > gcf ) { gcf = i; }; }; return gcf; };

Before using both numbers, I actually setup a for loop just to find the greatest factor of the first number. First, I setup gcf to hold the number and set it to one initially. Then, I setup this for loop:

for ( var i = 0; i < lower; i++ ) { if ( lower % i == 0 && i > gcf ) { gcf = i; }; };

This cycled over all of the numbers from 1 up to num1. If the remainder of num1/i was 0, it compared i to the current gcf value. If i was larger, gcf was set to i.

Now, I needed a way to incorporate the second number and find a commonality. First, I wanted to decrease the amount of computations possible. To do that, I could first start by finding the greatest common factor in the smallest number with the rationale that the gcf couldn’t be larger than the smallest number.

I setup variables for highest and lowest and arbitrarily set them to num2 and num1 respectively. Then, I had an if statement swap the values if necessary:

var higher = num2; var lower = num1; if ( num1 > num2 ) { higher = num1; lower = num2; };

Finally, I built the second number into my original for loop by including `higher % i == 0`

in the if block.

for ( var i = 0; i < lower; i++ ) { if ( lower % i == 0 && higher % i == 0 && i > gcf ) { gcf = i; }; };

Now, the only time the if block runs is when i is a common factor between both the highest and lowest numbers.

Solve it a different way? Please share!

The post Code Challenge: Greatest Common Factor appeared first on Jeremey DuVall.

]]>The post Code Challenge: Triple Double appeared first on Jeremey DuVall.

]]>Again, this week’s code challenge comes from my trusty favorite, Coderbyte:

Using the JavaScript language, have the function TripleDouble(num1,num2) take both parameters being passed, and return 1 if there is a straight triple of a number at any place in num1 and also a straight double of the same number in num2. For example: if num1 equals 451999277 and num2 equals 41177722899, then return 1 because in the first parameter you have the straight triple 999 and you have a straight double, 99, of the same number in the second parameter. If this isn’t the case, return 0.

Here are some test cases:

Input = 465555 & num2 = 5579 | Output = 1

Input = 67844 & num2 = 66237 | Output = 0

Here’s my solution collapsed:

function TripleDouble(num1, num2) { // Split the numbers into arrays var first = num1.toString().split(''); var second = num2.toString().split(''); // Loop over each item in the first array for ( var i = 0; i < first.length; i++ ) { var count = 0; // Compare the current array item to other items in the first array for ( var j = 0; j < first.length; j++ ) { // If the items match, increment our counter if ( first[i] == first[j] ) { count ++; }; }; // If we have a triple, let's compare against the second array if ( count >= 3 ) { // Set a second counter for the second array var dupe = 0; // Loop over the second array for ( var k = 0; k < second.length; k++ ) { // If the item from the first matches the item in the second, increment dupe if ( first[i] == second[k] ) { dupe++; }; }; // If dupe is greater than two, we have a double in the second array. Return 1. if ( dupe >= 2 ) { return 1; }; }; }; // If we made it this far, everything failed. Return 0. return 0; };

Full disclosure, this was done in one attempt. It’s not the cleanest code I’ve ever written, but it works (I think!).

First, we turn the numbers into strings and then split the strings into arrays so we can loop over them.

var first = num1.toString().split(''); var second = num2.toString().split('');

Next, we start a for loop to loop over the first array item:

for ( var i = 0; i < first.length; i++ ) { var count = 0; for ( var j = 0; j < first.length; j++ ) { if ( first[i] == first[j] ) { count ++; }; }; };

Inside the for loop, we run another for loop to compare against other numbers in the first array. If the array items match, we increment the counter variable. This way, we can see if there are any doubles or triples.

Next, we put an if statement inside the for loop to check if the count variable is greater than or equal to three. If it is, we want to loop over the second array:

if ( count >= 3 ) { var dupe = 0; for ( var k = 0; k < second.length; k++ ) { if ( first[i] == second[k] ) { dupe++; }; }; if ( dupe >= 2 ) { return 1; }; };

In the second array, we’re comparing the current item in the first array (first[i]) to the items in the second array (second[k]). If the items match, we increment our new counter variable dupe. After we’re done comparing the item to all items in the second array, we want to know if dupe is greater than or equal to 2. If it is, we’ve met our requirements (since we only enter this portion if count is at least 3). So, we can return 1.

If we make it to the very end, we can assume none of the conditions were true so we can return 0.

The post Code Challenge: Triple Double appeared first on Jeremey DuVall.

]]>The post Monthly Review: October 2015 appeared first on Jeremey DuVall.

]]>This month was a bit of an oddball because I was traveling quite a bit. First, I went to Park City, Utah for the Automattic Grand Meetup. It was an absolute blast! From there, I traveled down to Austin, Texas for a wedding. Then, Charlotte and I stayed in Austin the entire next week for a vacation and explored the city.

**Make Drink for Pink a success.**This was our first year running our little non-profit in Denver, Colorado. October is our big month since it’s Breast Cancer Awareness month. We don’t have the final numbers yet, but it looks like we’ll come in somewhere between $5,000-$6,000. I consider that a success!**Finish the Full-Stack JavaScript Treehouse Course.**I failed on this one. I got stuck on an Express video series that I just wasn’t excited about. The good news is I’m through that now and almost finished with the course.**Publish a coding challenge each week.**I missed one week during October (on vacation). Otherwise, I nailed it. 80% success.**Put out a code-related project.**Fail. I was doing relatively well with this in August/September. I put out a few code-related projects, but my progress has stalled since. In November, I’m going to launch a new project related to resumes/interviewing that hopefully will be an awesome resource.

I didn’t really set a habit to focus on for the month. However, here are some metrics that I tracked:

**Workouts:**20 (Goal of 20) – All tracked here**28-Day Average Steps:**11,986 (Goal of 10,000)

I only had one freelance piece published, but it was a bit of a doozy:

Automate Google Sheets: An Introduction to Google Apps Script

I had to learn Google Apps Script first in order to write the piece. I should have 2-3 pieces published in November.

- Mistakes Were Made (But Not By Me)
- The Martian
- Multipliers: How the Best Leaders Make Everyone Smarter

- Launch the interview/resume-related project (mainly HTML/CSS/JavaScript but I’m going to use Gulp as well for various things as practice)
- Publish 12 total blog posts here on my personal blog
- Finish the Full-Stack Treehouse course and Ember.js
- Publish 4 code challenges
- Publish 2 freelance pieces

**Meditation** – I tried focusing on this earlier in the year and making it a habit. Unfortunately, it didn’t stick. Success would be 20 days of meditating (using Coach.me to track).

*Featured Image: A morning trail run in Park City, Utah*

The post Monthly Review: October 2015 appeared first on Jeremey DuVall.

]]>The post Code Challenge: Consecutive appeared first on Jeremey DuVall.

]]>This week’s code challenge comes again from Coderbyte:

Using the JavaScript language, have the function Consecutive(arr) take the array of integers stored in arr and return the minimum number of integers needed to make the contents of arr consecutive from the lowest number to the highest number. For example: If arr contains [4, 8, 6] then the output should be 2 because two numbers need to be added to the array (5 and 7) to make it a consecutive array of numbers from 4 to 8. Negative numbers may be entered as parameters and no array will have less than 2 elements.

Here are some provided test cases:

Input = 5,10,15 Output = 8

Input = -2,10,4 Output = 10

Here is my solution collapsed:

function Consecutive(arr) { var highest = arr[0]; var lowest = arr[0]; var numbersBetween = []; for (var i = 0; i<arr.length; i++) { if (arr[i] > highest) { highest = arr[i]; } else if (arr[i] < lowest) { lowest = arr[i]; }; }; for (var j = lowest; j<=highest; j++) { if (arr.indexOf(j) == -1) { numbersBetween.push(j); }; }; return numbersBetween.length; };

The first step was to figure out the highest and lowest numbers in the array so I could start working on creating a consecutive array of numbers between them. I created two variables, `highest`

and `lowest`

. Both were set to the first array item in the beginning. Then, I looped over the array and set the highest and lowest accordingly:

for (var i = 0; i<arr.length; i++) { if (arr[i] > highest) { highest = arr[i]; } else if (arr[i] < lowest) { lowest = arr[i]; }; };

Now, I just needed to create a new array between the highest and lowest numbers. To do that, I created another for loop. I started at the lowest number and worked up to the highest in increments of one. I used `indexOf()`

to find out whether or not the number was in the original array. If it was not in the array already (`indexOf()`

returned -1), I pushed it onto a new array I called `numbersBetween`

. Then, I could just return the length of `numbersBetween`

.

Alternatively, I could have just setup a counter variable that was incremented. I setup the new array mainly because I was interested in logging out the array for testing/fun.

for (var j = lowest; j<=highest; j++) { if (arr.indexOf(j) == -1) { numbersBetween.push(j); }; };

The post Code Challenge: Consecutive appeared first on Jeremey DuVall.

]]>The post Code Challenge: Additive Persistence appeared first on Jeremey DuVall.

]]>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 thenumparameter 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 innumuntil you reach a single digit. For example: ifnumis2718then your program should return2because 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.

The post Code Challenge: Additive Persistence appeared first on Jeremey DuVall.

]]>The post Code Challenge: Number Search appeared first on Jeremey DuVall.

]]>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 Number*1*”

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.

The post Code Challenge: Number Search appeared first on Jeremey DuVall.

]]>The post Code Challenge: Blackjack appeared first on Jeremey DuVall.

]]>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”

For me, it was helpful to separate out the challenge into a few distinct parts:

- Turn the string values into actual numbers.
- Disregarding the possibility of an ace, create a function that could return the highest card in the hand.
- Disregarding the possibility of an ace, modify the function to also figure out the sum of the hand and whether or not it was above, below, or equal to blackjack.
- Deal with the possibility of an ace.

Here’s my solution collapsed:

var cardValue = { "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "jack": 10, "queen": 10, "king": 10 }; function BlackjackHighest(hand) { // Set variable for sum of hand var sum = 0; // Set variable for highest card in hand to two var highest = "two"; // Set a result variable (what we"ll return) var result; // Set two variables for dealing with an ace in the hand var acePresent; var aceValue; // Determine the highest card in the hand including hierarchy of face cards for (var i=0; i<hand.length; i++) { // Set them both to lowercase so I don"t have to worry about that var currentCard = hand[i].toLowerCase(); highest = highest.toLowerCase(); // We want to know if the card values are equal so we can establish hierarchy var cardsEqual = function () { if (cardValue[currentCard] == cardValue[highest]) { return true; }; }; if (cardValue[currentCard] > cardValue[highest]) { highest = currentCard; } else if (cardsEqual() && highest == "ten" && currentCard == "jack" || currentCard == "queen" || currentCard == "king") { highest = currentCard; } else if (cardsEqual() && cardValue == "queen" && highest == "jack") { highest = currentCard; } else if (cardsEqual() && cardValue == "king" && highest == "jack") { highest = currentCard; } else if (cardsEqual() && cardValue == "king" && highest == "queen") { highest = currentCard; }; // If there is an ace, let's know that and move on if (currentCard == "ace") { var acePresent = true; } else { sum += cardValue[currentCard]; }; }; // If an ace was present and the sum is less than 11 if (acePresent == true && sum < 11) { // The ace is worth 11 and it's the highest card aceValue = 11; highest = "ace"; // Add the ace value to the sum sum += aceValue; } else if (acePresent == true) { // Otherwise, it's worth one aceValue = 1; sum += aceValue; }; // Determine if we busted if (sum < 21) { result = "below"; } else if (sum = 21) { result = "blackjack"; } else { result = "above"; }; // Build the result and return it result += " " + highest; return result; };

I’ll walk through it in a series of steps:

Originally, I used a crazy long set of if statements. Thankfully, my buddy Nate reminded me I could create an object of key/value pairs.

var cardValue = { "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "jack": 10, "queen": 10, "king": 10 };

Next, I wanted a way to determine the highest card value in the hand so I could return it later and sum the cards. At this point, we’re still not dealing with aces at all. I setup a variable called `highest`

and assigned it the value of ‘two’ to start. I setup another called `sum`

that held the total for the hand. Then, I cycled over the cards. I grabbed the currentCard from the hand and compared it to the value of the highest card. Then, I ran several if statements to tease out the highest card in the hand based on the hierarchy. Finally, I added the value to the sum.

var sum = 0; var highest = "two"; for (var i=0; i<hand.length; i++) { // Set them both to lowercase so I don"t have to worry about that var currentCard = hand[i].toLowerCase(); highest = highest.toLowerCase(); // We want to know if the card values are equal so we can establish hierarchy var cardsEqual = function () { if (cardValue[currentCard] == cardValue[highest]) { return true; }; }; if (cardValue[currentCard] > cardValue[highest]) { highest = currentCard; } else if (cardsEqual() && highest == "ten" && currentCard == "jack" || currentCard == "queen" || currentCard == "king") { highest = currentCard; } else if (cardsEqual() && cardValue == "queen" && highest == "jack") { highest = currentCard; } else if (cardsEqual() && cardValue == "king" && highest == "jack") { highest = currentCard; } else if (cardsEqual() && cardValue == "king" && highest == "queen") { highest = currentCard; }; sum += cardValue[currentCard]; };

Now that we have the sum, we can figure out whether we’re at blackjack or not.

if (sum < 21) { result = 'below'; } else if (sum = 21) { result = 'blackjack'; } else { result = 'above'; };

At this point, we’re pretty darn close. We just need to figure out what to do with the ace.

While we’re cycling through the hand, we want to know whether or not an ace is present. Since the ultimate value of an ace is determined by the sum of the hand, we can’t do anything right away. I established two variables – `acePresent`

and `aceValue`

. Within the original for loop, I added a conditional:

if (currentCard == "ace") { var acePresent = true; } else { sum += cardValue[currentCard]; };

If an ace is present, I just want to move on. However, if the card isn’t an ace, let’s add it to the sum. Then, once we have counted all of the cards, I added this if statement outside the for loop:

if (acePresent == true && sum < 11) { // The ace is worth 11 and it"s the highest card aceValue = 11; highest = "ace"; // Add the ace value to the sum sum += aceValue; } else if (acePresent == true) { // Otherwise, it"s worth one aceValue = 1; sum += aceValue; }; sum += aceValue;

If an ace is present and the sum of all cards (minus the ace) is less than eleven, the ace is worth 11 and the highest card by default. Otherwise, the ace is worth one.

A big thank you goes out to Nate for pointing out areas of improvement in the comments section!

The post Code Challenge: Blackjack appeared first on Jeremey DuVall.

]]>The post Code Challenge: String Reduction appeared first on Jeremey DuVall.

]]>This week’s code challenge comes from Coderbyte. Here are the basic instructions:

Have the function `StringReduction(str)` take the `str` parameter being passed and return the smallest number you can get through the following reduction method. The method is: Only the letters a, b, and c will be given in str and you must take two different adjacent characters and replace it with the third.

For example, if you were provided the string “abc,” you could simplify that to “cc” but no further. On the other hand, “aba” could be simplified to “ca” and then to “b.” For simplification, here are all of the transformations:

`ac = b`

ca = b

cb = a

bc = a

ab = c

ba = c

Here are some test cases:

StringReduction(“abcabc”) should equal 2.

StringReduction(“cccc”) should equal 4.

StringReduction(“baccabcbc”) should equal 1.

Here’s my solution collapsed:

function StringReduction(str) { // Set initial counter variable to 0 var i = 0; // Split the string into an array of letters var letters = str.split(''); // Start do loop. do { // If the first and second letter in the array match any of the pairs if ((letters[i] == "a" && letters[i+1] == "b") || (letters[i] == "b" && letters[i+1] == "a")) { // Remove the second letter letters.splice(i+1, 1); // Transform the first letter letters[i] = "c"; // Set the counter back to 0 so we can start at the beginning again i = 0; } else if ((letters[i] == "b" && letters[i+1] == "c") || (letters[i] == "c" && letters[i+1] == "b")) { letters.splice(i+1, 1); letters[i] = "a"; i = 0; } else if ((letters[i] == "c" && letters[i+1] == "a") || (letters[i] == "a" && letters[i+1] == "c")) { letters.splice(i+1, 1); letters[i] = "b"; i = 0; // If no conditions are met, incremenet the counter } else { i++; } } while (i < letters.length); // Return the length of the transformed string return letters.length; } console.log(StringReduction("baccabcbc"));

The first step was to setup an initial counter variable for my do/while loop and break the string into individual letters. Next, I entered the do/while loop with the counter set to 0. There are a total of four comparison statements that check if any of the transformations are met. Each comparison statement checks both the forward (ab) and backward (ba) variations.

If the comparison is a match, the second letter in the group (i+1) is spliced from the array while the first letter (i) is transformed. Finally, the counter variable is set back to 0 so we can start again at the beginning of the array.

If the first three comparisons all fail, the counter is incremented by one. This do loop runs while the counter variable (i) is less than the length of the letters array.

I originally started with a for loop. That worked alright, but it moved continuously down the string rather than starting over on a transformation. For example, it would simplify “aabc” to “acc” but not to “bc” or “a.” The do/while loop allowed me to reset the counter when a transformation occurred.

The post Code Challenge: String Reduction appeared first on Jeremey DuVall.

]]>The post Code Challenge: Recurring Letters appeared first on Jeremey DuVall.

]]>This one was a bit of a doozy! I originally read this challenge three weeks ago and gave it a try. I couldn’t get it working so I moved on to another after an hour of frustration. Reflecting back on the “Second Greatest Length” challenge, I had a little epiphany of how it could work.

**Challenge:** Given a string, the function `highestRecurringLetter`

should return the word in that string that contains the highest recurring letter. For example, if given “Trees are great,” the function should return “Trees” because the letter ‘e’ occurs twice. If no letter occurs more than once in a word (“This is fun”), the function should return the last word in the string. Assume that the string has at least one word, and words are separated by spaces.

**Test cases**

`highestRecurringLetter("Soccer is fun")`

= ‘Soccer’;

`highestRecurringLetter("Recurring challenges are fun")`

= ‘Challenges’;

`highestRecurringLetter("I love them")`

= ‘Them’;

Here’s my solution minimized. I want to see yours though. If you give this a shot, let me know and post a link to your solution in the comments! Otherwise, just let me know what I could’ve done better!

<script> var highestRecurringLetter = function(string) { // Split the string into separate words var words = string.split(' '); // Set variables for highest recurring letter and the current leader var highestRecurring = 0; var leader = 0; var bestWord; // Loop over the words for (var i = 0; i < words.length; i++) { // For each word, split it into individual letters var letters = words[i].split('') // Loop over each letter for (var t = 0; t < letters.length; t++) { // Compare the letter to other letters in the string for (var x = 0; x < letters.length; x++) { // If the lowercase version of the letters match if (letters[t].toLowerCase() == letters[x].toLowerCase()) { // Increment the leader leader = leader + 1; } } // Compare the leader value to the current highestRecurring // If it's larger or equal to if (leader >= highestRecurring) { // Replace the highestRecurring value highestRecurring = leader; // Set the best word to the word including this letter bestWord = words[i]; // Set the leader back to zero leader = 0; // Otherwise, set the leader back to zero } else { leader = 0; } } } // Write out the information to the page var results = "The string provided was: " + string; results += "<br>" + "The word with the most recurring letters is: '" + bestWord; results += "'. It has a letter that occurs " + highestRecurring + " times." document.write(results) }; highestRecurringLetter('This is a lot of fun'); </script>

It looks a bit involved, but it really just involves quite a few loops. Here are the basics in sudo code:

- Split the string into individual words
- Setup variables to store the highest recurring and then the leader. The “`highestRecurring“` will store the highest recurring letter at any moment. “`leader“` will store the value of the current letter we’re counting.
- Loop over each word and split the word into individual letters
- For each letter in a word, loop over the other letters in the word. If the lowercase value of the letters match, increment the “`leader“` variable.
- Compare “`leader“` to “`highestRecurring“`. If it’s equal to or larger replace “`highestRecurring“` with `leader` and set leader back to 0. Otherwise, just set `leader` back to 0.
- Write the information to the page.

A few additional notes:

- In step #5, it’s important to set greater than or equal to. That way, if two words tie, the latter word in the string is returned.
- I
*really*didn’t want to use this many `for` loops, but I couldn’t think of another way to loop over the letters again for comparison.

The post Code Challenge: Recurring Letters appeared first on Jeremey DuVall.

]]>