SQL Saturday

This is a short post but the problems were still pretty fun!

Types of Triangles:

Given the table of triangles, sides find if a triangle is possible. If so then find the type of triangle that exists.

Triangle


The PADS

An OCCUPATIONS table that contains the following records:

Generate the following two result sets:

  1. Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).
  2. Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:

Creating your first .net app

I recently have been looking at more things to dive into and decided to try out .net. LinkedIn has 32,000 listings for .net positions in the U.S. so that also further peaked my interest. If you don’t know much about .net in broad strokes it is an open source platform that allows you to reach multiple platforms.

Screen Shot 2018-02-07 at 1.55.24 PM.png

I will be working off the Microsoft tutorials for most of the .net stuff I will be doing. If you haven’t used any of their documentation before it’s pretty awesome.

Install .Net SDK

Once installed go into your documents folder to create your first appScreen Shot 2018-02-07 at 5.36.10 PM.png.

 

 

 

After this is successful you can ls the directory to see the new app.

Screen Shot 2018-02-07 at 5.36.42 PM.png

 

 

Cd into the myApp directory.

Screen Shot 2018-02-07 at 6.03.14 PM.png

 

 

This is a very basic .net application. The commands for the Hello World output comes from the program.cs file found within the myApp folder. carbon.png

Next week I will be making a more complex .net project to share with you all! See you next time.

SQL Saturday

SQL Saturday

Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from STATION. Your result cannot contain duplicates.

SELECT DISTINCT CITY

FROM STATION

WHERE City like “A%” or City like “E%” or City like “I%” or City like “O%” or City like”U%”;

Query the list of CITY names ending with vowels (a, e, i, o, u) from STATION. Your result cannot contain duplicates.

SELECT DISTINCT CITY
FROM STATION
WHERE City like "%a" or City like "%e" or City like "%i" or City like "%o" or City like"%u";

Query the list of CITY names from STATION which has vowels (i.e., a, e, i, o, and u) as both their first and last characters. Your result cannot contain duplicates.

SELECT DISTINCT CITY
FROM STATION
WHERE City like "A%" AND (City like "%a" or City like "%e" or City like "%i" or City like "%o" or City like"%u") or
      City like "E%" AND (City like "%a" or City like "%e" or City like "%i" or City like "%o" or City like"%u") or 
      City like "I%" AND (City like "%a" or City like "%e" or City like "%i" or City like "%o" or City like"%u") or 
      City like "O%" AND (City like "%a" or City like "%e" or City like "%i" or City like "%o" or City like"%u") or 
      City like"U%" AND (City like "%a" or City like "%e" or City like "%i" or City like "%o" or City like"%u");

Query the list of CITY names from STATION that does not start with vowels. Your result cannot contain duplicates.

SELECT DISTINCT CITY
FROM STATION
WHERE City NOT like "A%" AND City NOT like "E%" AND City NOT like "I%" AND City NOT like "O%" AND City NOT like"U%";

Query the list of CITY names from STATION that does not end with vowels. Your result cannot contain duplicates.

SELECT DISTINCT CITY
FROM STATION
WHERE City NOT like "%a" AND City NOT like "%e" AND City NOT like "%i" AND City NOT like "%o" AND City NOT like"%u";

Fun with Select Queries

Query all columns for all American cities in CITY with populations larger than 100000. The CountryCode for America is USA. Input Format The CITY table is described as follows:

Screen Shot 2018-01-27 at 9.53.29 AM.png

SELECT * /*Selects all columns from table*/
FROM CITY /*selects table named city */
 /*only if the population is over100000 and the country is in the USA*/
WHERE POPULATION > 100000 AND COUNTRYCODE = 'USA';

Query the names of all American cities in CITY with populations larger than 120000. The CountryCode for America is USA.

SELECT NAME /*Selects NAME column from table*/
FROM CITY /*selects table named city */
/*only if the population is over 120000 and the country is in the USA*/
WHERE POPULATION > 120000 AND COUNTRYCODE = 'USA';

Query all columns (attributes) for every row in the CITY table.

SELECT * /*Selects all columns from table*/
FROM CITY; /*selects table named city */

Query all columns for a city in CITY with the ID 1661.

SELECT * /*Selects all columns from table*/
From CITY /*selects table named city */
WHERE ID = 1661; /*only if the city has an id of 1661 */

Query all attributes of every Japanese city in the CITY table. The COUNTRYCODE for Japan is JPN.

SELECT * /*Selects all columns from table*/
FROM CITY/*selects table named city */
WHERE COUNTRYCODE = 'JPN'; /*only if the country is in the japan*/

Query the names of all the Japanese cities in the CITY table. The COUNTRYCODE for Japan is JPN.

SELECT NAME /*Selects NAME column from table*/
FROM CITY/*selects table named city */
WHERE COUNTRYCODE = 'JPN'; /*only if the country is Japan*/

Query a list of CITY and STATE from the STATION table.

Screen Shot 2018-01-27 at 10.12.18 AM.png
SELECT CITY, STATE /*Selects the city and state columns from table*/
FROM STATION; /*reads from table*/

Query a list of CITY names from STATION with even ID numbers only. You may print the results in any order, but must exclude duplicates from your answer.
SELECT DISTINCT CITY /*selects distinct city name from a table */
FROM STATION /*uses table called station*/
WHERE (ID%2) = 0; /*only if the id is even*/

Let  be the number of CITY entries in STATION, and let  be the number of distinct CITY names in STATION; query the value of  from STATION. In other words, find the difference between the total number of CITY entries in the table and the number of distinct CITY entries in the table.

/*selects city count and distinct city name from a table and finds diff*/
SELECT COUNT(CITY) - COUNT( DISTINCT CITY) FROM STATION;

Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.

/*selects city name and string len from a table */
SELECT CITY, LENGTH(CITY)
/*selects from table named station */
FROM STATION
/*if the string len is the minimum */
WHERE LENGTH(CITY) = (SELECT MIN(LENGTH(CITY)) FROM STATION )
/*orders in alpha by city name */
ORDER BY CITY
/*takes only one from the list*/
LIMIT 1;

/*selects city name and string len from a table */
SELECT CITY, LENGTH(CITY)
/*selects from table named station */
FROM STATION 
/*if the string len is the maximum */
WHERE LENGTH(CITY) = (SELECT MAX(LENGTH(CITY)) FROM STATION)
/*orders in alpha by city name */
ORDER BY CITY
/*takes only one from the list*/
LIMIT 1;

 

Simple StopWatch

StopWatch by Developer Austin.

Screen Shot 2018-01-17 at 3.35.50 PM.png

This was my first actual published application for the Android Play Store and I loved the process! My goal for this project was to create a simple application and to try to learn as much as possible.

I used Android O to create and release so it is not available to everyone.

Download Page: https://play.google.com/store/apps/details?id=com.amsuarez.stopwatch

Application Design

Layout

Screen Shot 2018-01-17 at 3.38.32 PM.png
For this application, I used the constraint layout, Chronometer, ListView, and two Buttons. I went with a listview since it is easy to set constraints regardless of the device size. The chronometer seemed like a logical choice over Date since it had methods for starting and stopping. The start and stop buttons I placed at the bottom and placed colors so that it is easy to discern the differences at a glance.

Code

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Chronometer;
import android.os.SystemClock;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
   private Chronometer stopwatch;
   private List<String> timeList;
   private ListView timeElapsedList;
   private boolean timerStart = false;
   private ArrayAdapter<String> listAdapter;
   private int lapCount = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //sets up layout
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // setting stopwatch to chronometer
        stopwatch = findViewById(R.id.timeElapsed);

        //setting up listview
        timeList = new ArrayList<String>();
        timeElapsedList = (ListView) findViewById(R.id.timeListView);
        listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, timeList);
        // DataBind ListView with items from ArrayAdapter
        timeElapsedList.setAdapter(listAdapter);
    }

    public void startButton(View view) {
        // resets the start time
        stopwatch.setBase(SystemClock.elapsedRealtime());
        // starts the chronometer
        stopwatch.start();
        timerStart = true;
    }

    public void stopButton(View view) {
        stopwatch.stop();
        // if the start was pressed prior then stop process begins
        if (timerStart) {
            lapCount++;
            timeList.add("Lap " + lapCount + ": " +stopwatch.getText().toString());
            listAdapter.notifyDataSetChanged();
            stopwatch.setBase(SystemClock.elapsedRealtime());
            timerStart = false;
        }
    }

This was the first time I used the chronometer, I was originally going to use a Date variable but soon ran into some trouble. Using a Date variable I could measure the exact time elapsed; however, creating a visual transition of the time elapsed on the UI was difficult. I then picked the chronometer and my code was able to slim down since the methods the widget had been just what I needed.

Porting to the Store:

This was fairly easy to launch to the market since it did not use location or any other information from the user. In the future, I would like dive deeper into the Beta and Alpha testing processes in the Play Console.

Conclusion:

It was a fun simple project and I am definitely excited to do more projects like this!

If you are reading this and have any suggestions please message or comment. 😀

Mancala-AI

Mancala-AI

By Matt Corrente, Paul Miller, Luigi Sanchez, and Austin Suarez

Project Link: https://github.com/138paulmiller/Mancala-AI-Bot/blob/master/README.md

Summary

The Mancala AI is a project that I got to work on with some very talented programmers (Matt Corrente, Paul Miller, and Luigi Sanchez). Our project was to use artificial intelligence in a unique way. Although AI for games has been done we thought it would be interesting to do a study on how each AI algorithm can compete against one another. We built out it out three different AI algorithms ( Min-max with Alpha beta, Monte Carlo, and Evolutionary) to run on a Flask app.

About Mancala

“It’s an ancient family of board games, and there are numerous variants. Many different forms of Mancala are played across Africa, though the game may originally have come from ancient Sumeria.”[1]

Mancala is a two player turn-based board game.The goal is to capture the most beans and stones into your side.

Since Mancala is a game with a clear set of rules it allows for each AI to calculate a path to victory fairly. By fairly, we mean that some variations of this game are not perfect and allow for an extremely calculate the first move that is capable of ending the game.

 

Rules

  1. The Mancala board is made up of two rows of six holes, or pits, each.
  2. Four pieces—marbles, chips, or stones—are placed in each of the 12 holes.
  3. Each player has a store (called a Mancala) to the right side of the Mancala board.
  4. The game begins with one player picking up all of the pieces in any one of the holes on his side.
  5. Moving counter-clockwise, the player deposits one of the stones in each hole until the stones run out.
  6. If you run into your own store, deposit one piece in it. If you run into your opponent’s store, skip it.
  7. If the last piece you drop is in your own store, you get a free turn.
  8. If the last piece you drop is in an empty hole on your side, you capture that piece and any pieces in the hole directly opposite.
  9. Always place all captured pieces in your store.
  10. The game ends when all six spaces on one side of the Mancala board are empty.
  11. The player who still has pieces on his side of the board when the game ends capture all of those pieces.
  12. Count all the pieces in each store. The winner is the player with the most pieces. [2]

Algorithms

Mancala represents a decision problem since each player must decide on a single move to make. Each of our AI agents makes use of varying algorithms for decision making.

We used:

  • Minimax with Alpha-Beta Pruning
  • Monte-Carlo Tree Search
  • Evolutionary Algorithm with binary encoded moves

The algorithms we used vary in the method of deciding. For example, our Minimax, Monte-Carlo and Evolutionary algorithms make use of traversing the current game tree. However, both searching algorithms use different heuristics to limit the state space being search. The state space for an entire game is very large, and running an exhaustive search on the entire game tree will run in about O(6^n) time. Where n is a number of total turns, where each player has at most 6 choices. A naive exhaustive searching algorithm for this is completely inefficient, so adding a maximum lookahead depth allows us to bound the search space for our algorithms making them run in a reasonable enough time to play against.

 

Heuristics

All our algorithms make use of a variable heuristic function. This function analyzes the current state of the board to help the AI make the best possible decision. This heuristic can be used to:

  • Maximize AI’s score
  • Maximize the difference between the AI and players score
  • Maximize the number of pebbles on the AI side
  • Maximize the difference between the number of pebbles on AI side from player’s side

Or a weighted polynomial of the above (x = score, p = pebble diff = x+p*0.3)

Modifying the evaluation heuristic also changes the difficulty of the AI. For instance, in the Minimax algorithm, evaluating the score performs much better than evaluating a number of pebbles on each side. Also, measuring the relative score between the player and the AI performs better than just maximizing the AI. The reasoning behind this would be that the AI not only maximizes his own score but also makes sure that the next best move for the player will be far lower than the AI’s score. So, it would preference 9 vs 3 over 10 vs 8.

 

Playability

Each of our algorithms performs differently. The Minimax algorithm with Alpha-Beta pruning is a more exhaustive searching making it much slower but is also much more difficult to beat. With a turn lookahead depth of around 6-8, the AI is quick enough to play and very difficult to beat. However, if the lookahead is not set and the AI searches the entire game tree, the AI will be unbeatable, however, due to the time complexity of the game tree, the AI takes far too long to decide on a move even with alpha-beta pruning. So, both Monte-Carlo and Evolutionary Algorithm decision-making approaches are much more user-friendly. The Monte-Carlo algorithm makes uses of a probabilistic adversarial decision making, which chooses the other players most likely move. This allows the algorithm to be far less exhaustive making it capable of making more human-like decisions, since the enemy may not always choose the predicted move. The Evolutionary algorithm makes use of binary programs that encode possible moves for the AI. The populations are initialized randomly and evolved using probabilistic mutation and crossover. Each population is evaluated by testing the heuristic for each next potential move, and the moves with the highest scores are more likely to be chosen for reproduction.

Conclusion

This was a very interesting project. Since the game tree is simple enough to visualize, yet results in an exponential explosion of possible game states. Each AI plays the game differently thus it is very interesting to see the result from the AI vs AI.

Work Cited

[1] https://www.thespruce.com/how-to-play-mancala-409424

[2] https://www.thespruce.com/how-to-play-mancala-409424

Acrylic background and Fluent Design

Fluent Design

Acrylic background

Summary of what’s going on:

  1. Introduction to Fluent Design. 👨‍🏫
  2. Acrylic Backgrounds. 🎨
  3. How to implement. 🤯

Introduction👨‍🏫

Fluent Design

Fluent design is a massive Windows 10 UI change that took place in the fall creator’s update and it’s beautiful! Their idea was pretty simple the world/technology/life is getting more complicated, let’s make things simple let’s make thing fluent. For this new design system Microsoft hit four main points: Material, Light, Depth, Scale, and Motion. For this post I will be talking about acrylic material ; one of the material aspects of fluent design.

What is Acrylic Material 🎨

Acrylic material is a brush for UI to help add depth to your application. The key to use Acrylic material as an accent to other brushes and not as the main brush. An example would be using it in a pane, or as background with images or other material on top. The process on how it was designed is pretty cool, I placed a picture below but be sure to check the link at the end for more info.

Resources

  1. Visual Studio 17
  2. A UWP using Windows 10 fall creators update.

How to Implement 🤯

Implementing the Acrylic material as a background feature of Fluent Design is super simple. In the xaml page of your UWP add the Background=”{ThemeResource SystemControlAltLowAcrylicWindowBrush}”> to your Page section. There are a bunch of ways to play around and specialize the use of the material for more on that check the link at the end.

What I am using it for? 👨‍💻

I’m using it for my UWP software engineering project. I’m utilizing this and other fluent design features to turn an otherwise boring task app into an interactive productivity tool.

For more Information 📚

https://docs.microsoft.com/en-us/windows/uwp/design/style/acrylic

github folder: https://github.com/amsuarez01/Habit-Hamster/tree/uwp/Habit%20Hampster%20UWP

Deck of Cards Trick

Here is a great critical thinking problem that I heard.

Scenario:

You are blind folded and cannot see.

I hand you a deck of cards telling you that a 5 are faced up and placed randomly in the deck (the rest are face down)  and ask you to split the group of cards into two groups such that each group has the same amount of face up cards.

This problem is great because one it forces you to think outside of the box and since the question itself can be easily represented in a computer science context.

 

(please try before just looking at solution, there is a way to split with 100% accuracy)

WARNING SPOILERS  SOLUTION BELOW!!!! 

 

 

 

Explanation:

The amount of cards in the deck doesn’t matter nor does the position of the cards face up in the deck. We can represent the problem as an array with 1s (face up ) and 0s (faced down). We can assume that based on the questions the groups don’t need to have the original amount of face up cards (5 is odd and you can’t really split it up evenly). Thus we must think how can to place the two groups separately.  If you take the amount of flipped cards from anywhere in the deck and invert them no matter their current orientation and take them placing it into group one and the rest into group two you will have met the problem conditions and have the correct solution.

#include <iostream>
#include <random>

using namespace std;
 //Compiler version g++ 6.3.0

int main()
 {
 	int deck[52];
 	int temp;
 	int flipCards = rand()%52+1;

	int* groupOne;
	int* groupTwo;

	for(int index =0; index < 52; index++)
 	{
 		deck[index] = 0;
 	}
	for(int index = 0; index < flipCards; index++)
	{

		do{
 			temp = rand()%52;
 		}while(1 == deck[temp]);
 		deck[temp]=1;
 	}
	groupOne = new int[flipCards]();
	groupTwo = new int[52-flipCards]();

	for(int index =0; index < 52; index++)
	{
		cout << deck[index] << endl;
	}
 	cout << endl;
	for(int index = 0; index < flipCards; index++)
 	{
		deck[index]= abs(deck[index]-1);
		groupOne[index] = deck[index];
 		cout << groupOne[index];
	}
	 cout << endl;

	for(int index = flipCards; index < 52; index++)
	{
		groupTwo[index] = deck[index];
 		cout << groupTwo[index];
 	}
 	cout << endl;
	return 0;
 }