MilSats – May Day and the Russians

Monday is May Day and the Russians will hold their traditional parade in Red Square – which, by the way, is not so named because of communism. Here is a picture of some Spetsnaz (Russian Special Ops soldiers) in the snow.

Russian-Snow

In the course of the surprise combat readiness inspection units of the separate Airborne Spacial Task Force brigade is providing tactical assault and blocking the Severomorsk-3 airfield (Severomorsk, Murmansk region)

FreeCodeCamp and JavaScript: Friendly Date Ranges

For me, this is the last challenge in the Front End Certificate.  I started this back when the list was a LOT shorter, and I had already completed the final three challenges.  I may end up writing them up as blog posts if I get time, and if I get any requests…

For now, though, let’s take a look at this challenge on dates!

Here’s the assignment:

“Convert a date range consisting of two dates formatted as YYYY-MM-DD into a more readable format.

The friendly display should use month names instead of numbers and ordinal dates instead of cardinal (1st instead of 1).

Do not display information that is redundant or that can be inferred by the user: if the date range ends in less than a year from when it begins, do not display the ending year.

Additionally, if the date range begins in the current year and ends within one year, the year should not be displayed at the beginning of the friendly range.

If the range ends in the same month that it begins, do not display the ending year or month.

Examples:

makeFriendlyDates([“2016-07-01”, “2016-07-04”]) should return [“July 1st”,”4th”]

makeFriendlyDates([“2016-07-01”, “2018-07-04”]) should return [“July 1st, 2016”, “July 4th, 2018″].”

The hints:

And here’s the starter code:

function makeFriendlyDates(arr) {
  return arr;
}

makeFriendlyDates([‘2016-07-01’, ‘2016-07-04’]);

So, I started by getting the data I needed into variables.  We’ll always get two dates; they are in an array.  The first date can be split into three items using a dash separator (‘-‘), as can the second.  I added each of those to a new array, which now has two subarrays.  I can get the year, which is always the first item in each array (So, [0][0] and [0][1]).  I can get the month, the second item, and the day, the third item.

I then created two “helper” functions, which are not IN the makeFriendlyDates() function – they are standalone.  The first, getMonth, uses a switch function to assign a month to the number sent from the second values in the arrays.  The other, get date, uses a bunch of if…then statements to convert the number of the day to an ordinal value – so, 01 becomes 1st, o2 becomes 2nd, 17 becomes 17th, and so on.

So, I thought, now I was all set.  I knew the year, so I could just throw together a couple of if…then statements based on what the dates were and I was good to go right?

As always, not right.

Most of it WAS easy – the base case, returning all the years, months, and days, was easy, as was the case where the years were the same, the year and month the same, and the day, month AND year the same.

But then there were two cases that weren’t working – when they were in different years, and less than /more than 365 days.  I could get one or the other to work but not both at the same time.  I was baffled.  So I did some research on the Date() method.

You can’t just subtract 365 to get the days in between, of course, and so I had to find a way to figure the amount of days in between the dates.  You can get that by sending the day, month and year to Date() and it will return the amount of time, in milliseconds(!) since January 1, 1970 (!!).  I have no idea who picked that date; I assume (and hope) there’s a reason for it.  In any case, that gives you the difference between the two dates in milliseconds which can be converted to days through a bit of math.

But it STILL wasn’t working for me.  And then I got it.

 

See, some of the dates were 2016…which is the current year.  So, the rule for that was a little different, and so I introduced a variable to get the current year.  If it was the current year, then the new rule applied….and that solved the last item!

 

My answer is below.  As always, ask questions if you have any, and I’ll be glad to answer them as best I can!

function makeFriendlyDates(arr) {
  var dates = [];
  var data = [];
  var thisYear = new Date().getFullYear();
  for (var item in arguments) {
    dates.push(arguments[item]);
  }
  var first = dates[0][0].split(‘-‘);
  data.push(first);
  var second = dates[0][1].split(‘-‘);
  data.push(second);
  var year1 = data[0][0];
  var year2 = data[1][0];
  var month1 = data[0][1];
  var month2 = data[1][1];
  var date1 = data[0][2];
  var date2 = data[1][2];
  var msPerDay = 1000 * 60 * 60 * 24;  // 1000ms/s * sec * min * hrs
  var calDate1 = new Date(year1, month1, date1);
  var calDate2 = new Date(year2, month2, date2);
  var diff = calDate2 – calDate1;
  var dateDiff = Math.round(diff/msPerDay);
  month1 = getMonth(month1);
  month2 = getMonth(month2);
  date1 = getDate(date1);
  date2 = getDate(date2);
  var firstDate;
  var secondDate;
  var answer = [];
  var yearOne = parseInt(year1);
  if(year1 === year2 && month1 === month2 && date1 === date2) {
    firstDate = month1 + ” ” + date1 + “, ” + year1;
    answer.push(firstDate);
  } else if (year1 === year2 && month1 === month2) {
    firstDate = month1 + ” ” + date1;
    secondDate = date2;
    answer.push(firstDate);
    answer.push(secondDate);
  } else if (year1 === year2) {
    firstDate = month1 + ” ” + date1 + “, ” + year1;
    secondDate = month2 + ” ” + date2;
    answer.push(firstDate);
    answer.push(secondDate);
  } else if(yearOne === thisYear && dateDiff < 365) {
    firstDate = month1 + ” ” + date1;
    secondDate = month2 + ” ” + date2;
    answer.push(firstDate);
    answer.push(secondDate);
  } else if(dateDiff < 365) {
    firstDate = month1 + ” ” + date1 + “, ” + year1;
    secondDate = month2 + ” ” + date2;
    answer.push(firstDate);
    answer.push(secondDate);
  } else {
    firstDate = month1 + ” ” + date1 + “, ” + year1;
    secondDate = month2 + ” ” + date2 + “, ” +  year2;
    answer.push(firstDate);
    answer.push(secondDate);
  }
  return answer;
}
function getMonth(month) {
  switch(month) {
    case ’01’:
      month = ‘January’;
      return month;
    case ’02’:
      month = ‘February’;
      return month;
    case ’03’:
      month = ‘March’;
      return month;
    case ’04’:
      month = ‘April’;
      return month;
    case ’05’:
      month = ‘May’;
      return month;
    case ’06’:
      month = ‘June’;
      return month;
    case ’07’:
      month = ‘July’;
      return month;
    case ’08’:
      month = ‘August’;
      return month;
    case ’09’:
      month = ‘September’;
      return month;
    case ’10’:
      month = ‘October’;
      return month;
    case ’11’:
      month = ‘November’;
      return month;
    case ’12’:
      month = ‘December’;
      return month;
  }
}
function getDate(date) {
  date = parseInt(date, 10);
  if(date === 1) {
    date = date + “st”;
  } else if (date === 2) {
    date = date + “nd”;
  } else if (date === 3) {
    date = date + “rd”;
  } else if (date >= 4 && date <= 20) {
    date = date + “th”;
  } else if (date === 21) {
    date = date + “st”;
  } else if (date === 22) {
    date = date + “nd”;
  } else if (date === 23) {
    date = date + “rd”;
  } else if (date >= 24 && date < 31) {
    date = date + “th”;
  } else if (date === 31) {
    date = date + “st”;
  }
  return date;
}
makeFriendlyDates([“2016-12-01”, “2017-02-03”]);

Theology 101: A Little Aquinas, Part I

In my quest to learn theology, I’ve found that you need to have an understanding of the writings of those who have gone before you.  This is a daunting task, as anyone who has seen Barth or Tillich‘s Systematic Theology tomes.  I discovered, to my delight, a series of books called The Armchair Theologian.  These summarize the views of many of the most important theologians of the past, such as Barth, Wesley, and Augustine.  They are not free from bias; of course every author brings his or her bias to what the write and the various authors that wrote these summaries are no exception.  Also, these are introductions and overviews; they are not by any means complete descriptions of the various theologians beliefs and works!  For that, you should always go to the original source.  But these are good beginner’s surveys.

 

Today I’d like to start by looking at Thomas Aquinas. Let’s jump right in; you can find the book information at the end of the post!

Chapter 1: Beginnings

In Chapter 1: Beginnings, Renick begins by noting that Aquinas’ “theory of natural law shaped our modern concept of human rights.  His views of the state supplied the model for Jefferson in the Declaration of Independence.”  He is the one who came up with the concepts of Jus in bello and Jus ad bellum, and he is the one who came up with many of the most well-known proofs of the existence of God.  Aquinas’ thinking was in reaction to the new universities springing up and the Muslim ideas being brought back by the crusaders.  He wanted to show that “the truths of the Bible and the truths of Christianity could be shown to have a rational basis”  and used reason to prove it.

Aquinas was born around 1225 in Aquino, between Rome and Naples.  He was the youngest of seven sons, and was sent to the Benedictines at 5 yrs old; despite this, he liked it.  He studied Aristotle at the University of Naples at 14 (including Politics, ethics, and Metaphysics).  Note that Aristotle was considered dangerous because his books conflicted with Church teachings.  After University, Thomas joined the Dominicans and took a vow of poverty, which didn’t sit well with his family.  Two of his brothers tried to talk him out of it, supposedly hiring a prostitute who tried to seduce Thomas.  Instead he fended her off with a fireplace poker, drew a cross on the wall, and begged God to grant him constant virginity, which appears to have happened.  Bernard Gui, Thomas’ biographer, wrote “From that time onwards, it was his custom to avoid the sight and company of women – except in case of necessity or utility – as a man avoids snakes.” Despite this his writings on sex have been influential.  Also,  he was apparently a chubby fellow and had a good memory.

Summa Theologica is over two million words.  The eidetic and eclectic Aquinas integrated the Bible, Aristotle (“The Philosopher”), Augustine, Jerome, Maimonides, Averroes, Avicenna, and others into it.  He gave sermons, and was a professor at the University of Paris, beginning his lectures at 6:00 AM – amazingly, they were well-attended.  He died in 1274, the Summa unfinished.

Thomism was condemned 3 years later as it used Aristotle who was considered to be heretical.  This was done by the Archbishop of Paris and the Archbishop of Canterbury.  But since the pagans and Jews did not accept the Bible as true, one had to appeal to reason, and so his ideas became needed to defend the faith.  In 1323, a few years after the lifting of the ban, the Church initiated the process of making Thomas a saint.  The poker incident was one of two miracles needed for sainthood; the other was the fact that on his deathbed, he asked for herring, although it wasn’t the season for them, and it just so happened that a fishing boat came in that day with…a herring.

In 1879, Pope Leo XIII declared Thomism to be official theology of the Roman-Catholic Church.  This was reiterated by John Paul II in his encyclical Faith and Reason.

Chapter 2: Humans, Angels, and God

Reason needs faith – not everything can be proved by reason alone, such as the Trinity.  These things must be revealed.

Faith needs reason – Aquinas felt that “human beings are unique, somewhat like the animals and somewhat like the angels but identical to neither.” Animals learn things using their senses, but angels can’t because they don’t have physical bodies.  So, they learn using their “intellect,” which Aquinas defines as “the ability to know truths intuitively, to experience things…on a direct intellectual level,” in much the same way that we “know” we are in love.  The angels thus know metaphysical truths and can know and experience God in a way that a dog cannot.

Humans, thus, can do both.  Morals cannot be empirically established, but are “known” metaphysically.  However, since we are both physical and intellectual, we are not as good as the angels at knowing things purely intellectually.  Our physical senses can confuse us.  But, since God made us with both types of senses, we should use both types of senses to understand the cosmos and know God.  This includes using your reason and intellect but also your physical senses (one reason that depending only on faith healing is wrong). “Science and medicine are a testimony, not a threat, to God’s design.”

“…Aquinas writes, ‘It is impossible for items that belong to reason to be contrary to those that pertain to faith.” If the belief is ‘true’, then faith has nothing to fear of it.  If the belief is false, then it cannot be a dictate of reason.”

Aquinas had five proofs of God’s existence, often called the “Five Ways” and that present the same argument five parallel ways.  The first is the argument from motion.  Empirically: Things move.  Whatever is moved must be moved by another.  So, something must have started the movement, and this is the “First Mover“.  This, Aquinas says, is God (although this does not prove the existence of the Christian God).  Immanuel Kant says, however – what moved the First Mover?  If you don’t need anything, then why do you need a first mover?

Several other philosophers such as Etienne Gilson have rebutted Kant.  Today, science relegates the role to nature as the first mover, but, the question remains, “How does ‘nature’ in this sense differ from the “God” of the religious believer?  What do we mean by “God” other than, in the first instance, that force which generated the cosmos?…who or what caused the Big Bang?  Where did the matter that exploded come from in the first place?”

The other four are the First Cause, the Argument from Contingency, the Argument from Degree, and the Teleological Argument (or Argument from Design).

Aquinas also felt that reason could tell us some things about God’s nature.  He said that God is immutable (unchangeable) in every way.  His reasoning was that if God had changed it would be for better or worse.  “If God is perfect, he could not have changed for the better or he would not have been perfect.  He could not have changed for the worse, or He would not now be perfect.”  The author notes that this does not take into account a morally neutral change.  This belief, that God doesn’t change at all, is still strongly held today by most Christians.

So, since “God is the author of a reasonable universe…what we know and say about [Him] should be reasonable” as well.

 

Source: Aquinas for Armchair Theologians, Timothy M. Renick, Westminster John Knox Press, Louisville, KY 2002

FreeCodeCamp and JavaScript: Make a Person

So as I mentioned, I’ve already finished the other FreeCodeCamp Advanced Algorithms.  Right now I need to complete the Simon game in order to get my Front End Certificate.  I hope to do that this week, but in the meantime, I may go over some of the rest of the challenges.  Here’s the next one, “Make a Person“.

So, here are the instructions:

Fill in the object constructor with the following methods below:

getFirstName()
getLastName()
getFullName()
setFirstName(first)
setLastName(last)

setFullName(firstAndLast)

Run the tests to see the expected output for each method.

The methods that take an argument must accept only one argument and it has to be a string.

These methods must be the only available means of interacting with the object.

For hints, FreeCodeCamp gives us:

Here are some helpful links:

Finally, the starter code:

var Person = function(firstAndLast) {
    return firstAndLast;
};
var bob = new Person(‘Bob Ross’);

bob.getFullName();

I have to admit that this one was pretty easy for me, since I have a Java course under my belt, which had already introduced me to set() and get() methods.  These allow you to set the properties individually, since you cannot access the actual variables themselves.  You send your value to these methods and they store the value inside the function.  You can read about this at the link on closures above.

So, I take the input and break it apart, assigning the elements of the array to the various corresponding methods.  I have three set methods and three get methods, as per the instructions. The various tests call the different methods, and the values change with the calls.  So, here’s my solution; feel free to ask questions in the comments.

var Person = function(firstAndLast) {
    var name = firstAndLast.split(‘ ‘);
    firstName = name[0];
    lastName = name[1];
    var fullName = firstAndLast;
    this.getFirstName = function() {
        return firstName;
    };
    this.getLastName = function() {
        return lastName;
    };
    this.setFirstName = function(first) {
        firstName = first;
    };
    this.setLastName = function(last) {
        lastName = last;
    };
    this.setFullName = function(firstAndLast) {
        fullName = firstAndLast;
    };
    this.getFullName = function() {
        return firstName + ” ” + lastName;
    };
    return firstAndLast;
};
var bob = new Person(‘Bob Ross’);
bob.getFullName();

Math 101: An Occasional Series

Six years ago I was laid off from an engineering job, and I decided it was time, after 16 years in the field, to review some of the fundamentals that I had forgotten in the intervening time.  One of my co-workers, before I left, had been working with his daughter on Algebra using the site Purple Math.  I also read James Gleick’s book Chaos at that time, and that got me interested in doing a little exploring.

I started by reviewing geometry, algebra, calculus, and differential equations using the The Easy Way series.  I checked them out of the library and this led me to reading some of the other books on the shelves there. I came to realize that there was a whole world of mathematics that I really had no idea existed, especially after I made the attempt to read a math paper from arXiv and realized that I had no idea what the first paragraph was saying.  Hilbert Spaces?  Riemannian Geometry? Topological forms? Rings? Lie Groups?  What were these things?  More importantly, why had we not studied those in school?  They were interesting, much more interesting, than the calculations that I had to master in high school and college.

In any case, I’ve found that math is also important in programming, both for solving problems like the permutations program that I covered recently, as well as others.  It’s also important for designing algorithms, and so on.  Logic is a part of mathematics and is the basis for all computer programs.

So what I’d like to do in this occasional series is look at some of the concepts I come across in the course of learning to program.  I figure the first couple will look at permutations, and some basic set theory.  I will also look at the trials and tribulations I am having of learning to put math equations in LaTeX for my blog posts!

FreeCodeCamp and JavaScript: No Repeats Please

No Repeats Please had me baffled for awhile, I’ll admit.  Recursion is a concept I still struggle with, and it’s really the key to the solution.

Here’s the description of the problem:

“Return the number of total permutations of the provided string that don’t have repeated consecutive letters. Assume that all characters in the provided string are each unique.

For example, aab should return 2 because it has 6 total permutations (aab,aab, aba, aba, baa, baa), but only 2 of them (aba and aba) don’t have the same letter (in this case a) repeating.”

The hints are:

Permutations – this is basically finding all the ways that a combination of items can be rearranged.  So, for example, if you have three letters (as in this exercise) you can rearrange them six ways – abc: abc acb bac bca cab cba.  There’a whole lot of theory here; go ahead and explore the link if you’d like.

RegExp – Regular Expression.  We’ve touched on these before, and I noted then that this was good for about a dozen posts.  So I suggest that you check out the page on MDN.

Here’s the code they give you to start with:

function permAlone(str) {
  return str;
}

permAlone(‘aab’);

Yes, well, that’s very helpful guys.  Thanks for that.  Very not helpful.

I had really no idea how to start.  I mean, I could see that I needed to loop through the string, I could use substr() to give me parts of the string that I could recombine to get the different permutations, and that it would involve some sort of recursion to go through the substrings, but beyond that, I was a little baffled.  So, step 1, Google it!

It turns out there are a TON of permutation algorithms out there.  But I didn’t want to just copy one – as I’ve noted in almost every previous blog post on a challenge, you don’t learn anything if you just copy and paste.  So I started deconstructing them, taking them apart, trying to figure out how they worked and what each part did.  Some of them, I found, were way too complicated and could be done an easier way.  Others were obviously written by someone with a lot of experience; they used all kinds of shortcuts.  Each one had a different concept of what should be included in what scope.  So when you look at my code below, remember that this is just the way I did it, and that there are many other ways.

function permAlone(str) {
  var perms = [];

  var string = str;

Perms is an array that’s going to hold all the permutations; string holds the string value that you want permuted.

  permute(str);
  function permute(string, letterIndex) {

So, when you first pass the values to the function, the first letter hasn’t been set yet, so we set it to 0.  You’ll see why we did this below.

  if (letterIndex == null) {
    letterIndex = 0;
  } else {
    letterIndex = letterIndex;
  }

When we hit the end of the string, push the value to an array that’s going to hold all the permutations.

    if (letterIndex == string.length) {
        console.log(string);
      perms.push(string);
        return;
    }
    for(var i = letterIndex; i < string.length; i++) {
      var s1;
        if (i > letterIndex) {
            s1 = string.substring(0, letterIndex) + string[i] + string.substring(letterIndex + 1, i) + string[letterIndex] + string.substring(i + 1);
        } else {
            s1 = string;
        }
        permute(s1, letterIndex + 1);
    }
}
  return perms.length;

}

This is the heart of the function.  We’re looping through the string, and recombining the letters in a string named ‘s1’.  Then we call permute() again from WITHIN permute() until we have hit the end of the string.  This is called recursion and, to my mind, is one of the hardest concepts in programming to master.  But it’s very powerful and if you can get it, it will open up a whole new world to you.  The easiest way to figure out what is going on here is to write it out by hand at each step, watching how the values change.

Finally, we call the function on a string:

permAlone(‘aab’);

But, this isn’t quite right yet.  The idea here is to delete all the permutations that have the same letter in a row, and return the amount of entries left, whereas the code above merely returns the number of permutations the string has.  Theoretically, we didn’t even need to write this code to figure out the number of permutations; we could have just taken the number of items – 3, and found its factorial – 3!, which is 3 x 2 x 1 or 6, and returned that number.  Instead, we generated all the permutations so that we could determine which ones had duplicate letters.  So let’s look at how to do that now.

So, my first attempt to get rid of the ones that had two of the same letters went like this:

  for (var item in perms) {
    console.log(perms[item]);
    if(perms[item].match(/\w{2,}/)) {
      perms.splice(0,1);
    }

  }

Note my use of a regular expression there, as per the hints.  Unfortunately, all this did was delete duplicate ENTRIES in the array – so instead of {aab, aab, aba, aba, baa, baa} for example, I ended up with {aab, aba, baa} which was not exactly what I was looking for.  So it was back to the drawing board…

Update:  Got it!  The filter() function should be familiar from my post here and the Inventory Update challenge.  The Regex threw me for awhile though.  I kept trying /w, from the MDN page, and not getting an answer.  Then I figured out that it was literally looking for a ‘w’.  The period was the right symbol to use to match any character.  I also had no parentheses around my period, which is for capture.  This ‘remembers’ the character, so it can match it to the previous character in the string.  Finally, I tried it as an if statement and that got messy.  So I just condensed the statement to return the items that needed to be in the array (answer).  I forgot the not symbol at first ( the !) and I kept getting it wrong until I figured out that I was getting the opposite of what I wanted, and that made me realize I was returning the wrong set of strings.  So, here’s the final solution:

function permAlone(str) {
  var perms = [];
  var string = str;
  permute(str);
  function permute(string, letterIndex) {
  if (letterIndex == null) {
    letterIndex = 0;
  } else {
    letterIndex = letterIndex;
  }
    if (letterIndex == string.length) {
        //console.log(string);
      perms.push(string);
        return;
    }
    for(var i = letterIndex; i < string.length; i++) {
      var s1;
        if (i > letterIndex) {
            s1 = string.substring(0, letterIndex) + string[i] + string.substring(letterIndex + 1, i) + string[letterIndex] + string.substring(i + 1);
        } else {
            s1 = string;
        }
        permute(s1, letterIndex + 1);
    }
}
var answer = [];
  answer = perms.filter(function(item) {
    return !item.match(/(.)\1+/);
  });
  return answer.length;
}

permAlone(‘aab’);

Okay, on to the next challenge, which is Friendly Date Ranges!