Friday, February 26, 2016

CS 2420 - Assignment 4 - Part 5

So now that I am done with the List class, I have moved on to another part of the assignment. This time I have to plot the running times of my sorts.

After thinking about it for a while, I decided that I would create a new class that would just be called from the Main function and it would sort lists of different sizes and it would output the time in milliseconds to a text file. This would make it easier to actually make a graph for each sort. In a graph, X would be the number of elements in the list and Y would be the time it took to sort the list.

Here is what I have for this new class:

using System;
using System.Diagnostics;
using System.IO;

class RunningTimes
{
    public static void SortPlot(ISorter sorter, int elements, string name)
    {
        Random randint = new Random();
        Stopwatch watch = new Stopwatch();
        StreamWriter file = new StreamWriter(@"ChristianMunoz_RunningTimes.txt", true);
        long time = watch.ElapsedMilliseconds;
        int[] list;

        while(elements > 0)
        {
            list = new int[elements];

            for (int i = 0; i < list.Length; i++)
                list[i] = randint.Next(1, 200);

            watch.Reset();
            watch.Start();
            sorter.sort(list, 0, list.Length);
            watch.Stop();
            time = watch.ElapsedMilliseconds;
            Console.WriteLine(time);

            file.WriteLine("Sort: {0} Element count: {1} Time in Milliseconds: {2}", name, elements, time);

            elements = elements - 10000;
        }
        file.WriteLine(" ");
        file.Close();
    }
}

In the part that says: @"ChristianMunoz_RunningTimes.txt" that is the location and name of the text file I'm creating. You can change the name to anything you want, and you can find the file in your pc by first going to the folder where you have your C# work: Documents\CSharp\DataStructuresAndSorts\Assignment4\bin\Debug. Or you can also replace the name and tell Visual Studio a specific location by pasting in a path that you want.

This is how I call the function from my main:

RunningTimes.SortPlot(qSorter, 70000, "Quick Sort");

Since this new class isn't doing anything special, I don't have to create a new instance of the class and I can just call it from my other file. In the above example: I pass in a Quick Sort object, I tell it how big I want my list to be (in this case it will be 70000 integers), and just for kicks I pass in a string to make it easier to read the txt file of the sort that I am on. The output of the file will look like this:

Quick Sort Element count: 70000 Time in Milliseconds: 93
Quick Sort Element count: 60000 Time in Milliseconds: 72
Quick Sort Element count: 50000 Time in Milliseconds: 48
Quick Sort Element count: 40000 Time in Milliseconds: 37
Quick Sort Element count: 30000 Time in Milliseconds: 20
Quick Sort Element count: 20000 Time in Milliseconds: S
Quick Sort Element count: 10000 Time in Milliseconds: 2

That's all for now, thanks for reading!

Thursday, February 25, 2016

CS 2420 - Assignment 4 - Part 4

Since last time I have been working on implementing my own Enumerator in my List class. I started to work on it Tuesday night while in class, but I was actually stuck on this assignment until earlier today when I figured it out.

Here is the finished Enumerator class:

private class myEnumerator : IEnumerator
{
    private MyList myList;
    private int index;

    public myEnumerator(MyList myList)
    {
        this.myList = myList;
        index = -1;
    }

    public bool MoveNext()
    {
        index++;
        return (index < myList.Count);
    }

    public T Current
    {
        get
        {
            return myList[index];
        }
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

    // Not Needed
    public void Dispose()
    {
        //Not Needed
    }

    public void Reset()
    {
        index = -1;
    }
}

This new class is embedded in the List class, and it just spits out the next item in the list. The cool thing about this new Enumerator is that it will stop as soon as it reached the Count of the items in the list instead of the length of the array. This way if there are any empty slots in the array, they won't get printed in the list.

That's all for now, thanks for reading!

Wednesday, February 24, 2016

Python Script for Work

So a few months ago I got a job working as a software tester at a company now called Willis Towers Watson. I have to say that I have loved working there, and its also given me an opportunity to keep working on expanding my knowledge of writing code.

A couple days ago, I was actually in the middle of testing an internal tool that we use to send client information to insurance providers. This tool generates XML files from the information that we collect from our customers, and then transmits the information to the insurance providers. We call these tools "dispatchers", and each carrier/provider has its own dispatcher that we use to send the information.

Whenever there is an update to a dispatcher, we have to generate the new XML files to make sure that they have the correct information. But this process can take a while since we have to go manually check each line of the XML to make sure that the information is there. This can get tedious and its just not efficient.

One of my team mates mentioned to me that it would be nice if there was a program we could use to check verify the changes instead of doing it by hand. This got me thinking, and I realized that it wouldn't be very hard to get something working. So today I spent part of the day working on a Python script that I could use to verify the updated XML files. Here is what I wrote:

import sys
def search_xml(term_line, xml_path):
xml = open(xml_path, 'r')
for xml_line in xml:
if term_line in xml_line:
print("Found: " + term_line + " In:" + xml_line)
def main():
xml_path = input("Enter file path for the XML: ")
terms_path = input("Enter file path for the search list: ")
print("")
try:
terms = open(terms_path, 'r')
temp = open(xml_path, 'r')
except OSError:
print("Unable to find one or more of those files, try again. \n")
main()
for term_line in terms:
term_line = term_line.strip('\n')
search_xml(term_line, xml_path)
rerun = input("Do you want to run the script again? Y/N ")
print("")
rerun = rerun.lower()
if rerun == "y":
main()
else:
sys.exit()
if __name__ == '__main__':
main()
view raw Reader.py hosted with ❤ by GitHub

This script takes two files, one file is the XML that we want to look at and the other is just a simple text file with all the tags that you want to verify that have been added/removed from the XML. I then simply print the tags that were found in the file and done.

While testing my code I found that there is a limitation to my script. For example: if I am looking for a tag call Name, the script will say that it has found the tag in the StateName or DoctorName tags. I haven't had time to work on it further, but hopefully I can figure out a way to search for an exact match only. But if not, I still think that my script will cut down in the time it takes for us to check XML files.

Anyways, that's all for now. Thanks for reading!

Monday, February 22, 2016

CS 2420 - Assignment 4 - Part 3

Its been a few days since my last entry, and I have to say that I have made a lot of progress with my List class. I have now finished everything except for creating my own Enumerator. I still haven't figured out how to write that part, hopefully it won't be too hard.

Here is what I have so far:

using System;
using System.Collections;
using System.Collections.Generic;

class MyList : IList
{
    private T[] underlyingArray;
    private int element_count;

    public MyList(int initial_size)
    {
        underlyingArray = new T[initial_size];
        element_count = 0;
    }

    public T this[int index]
    {
        get
        {
            return underlyingArray[index];
        }

        set
        {
            underlyingArray[index] = value;
        }
    }

    public int Count
    {
        get
        {
            return element_count;
        }
    }

    private void UpdateCount(int amount)
    {
        element_count += amount;
    }

    public bool IsReadOnly
    {
        get
        {
            return underlyingArray.IsReadOnly;
        }
    }

    public void Add(T item)
    {
        try
        {
            underlyingArray[Count] = item;
            UpdateCount(1);
        }
        catch (IndexOutOfRangeException)
        {
            Resize(underlyingArray);
            Add(item);
        }
    }

    public void Clear()
    {
        for (int index = 0; index < Count; index++)
            underlyingArray[index] = default(T);

        UpdateCount(-Count);
    }

    public void Resize(T[] array)
    {
        T[] newArray = new T[array.Length * 2];

        for (int index = 0; index < array.Length; index++)
            newArray[index] = array[index];

        underlyingArray = newArray;
    }

    public bool Contains(T item)
    {
        for (int index = 0; index < Count; index++)
            if (EqualityComparer.Default.Equals(underlyingArray[index], item))
                return true;
        return false;
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        if (Count == array.Length)
            Resize(array);

        for (int index = Count; index > arrayIndex; index--)
            array[index] = array[index - 1];

        underlyingArray = array;
    }

    public IEnumerator GetEnumerator()
    {
        for (int i = 0; i < underlyingArray.Length; i++)
            yield return underlyingArray[i];
    }

    // TODO No yield
    public IEnumerator GetEnumeratorNoYield()
    {
        throw new NotImplementedException();
    }

    public int IndexOf(T item)
    {
        for (int index = 0; index < Count; index++)
            if (EqualityComparer.Default.Equals(underlyingArray[index], item))
                return index;
        return -1;
    }

    public void Insert(int index, T item)
    {
        if (Count == underlyingArray.Length)
            Resize(underlyingArray);
        if (index >= Count)
            Add(item);
        else
        {
            CopyTo(underlyingArray, index);
            underlyingArray[index] = item;
            UpdateCount(1);
        }
    }

    public bool Remove(T item)
    {
        for (int index = 0; index < Count; index++)
            if (EqualityComparer.Default.Equals(underlyingArray[index], item))
            {
                RemoveAt(index);
                return true;
            }
        return false;
    }

    public void RemoveAt(int index)
    {
        while (index < Count - 1)
        {
            underlyingArray[index] = underlyingArray[index + 1];
            index++;
        }
        UpdateCount(-1);
        underlyingArray[Count] = default(T);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

I know that I probably still need to fix a bunch of stuff in my class, but for now I think I'm done with it. I will now focus on writing functions that put my List class to the test.

That's all for now, thanks for reading!

Wednesday, February 17, 2016

CS 2420 - Assignment 4 - Part 2

So I have now finished the first part of this assignment, and I have now moved on to creating a List class using the IList interface and Generics.

I am going to be honest here, I had no idea how to start this part of the assignment. At first I thought I was building another Linked List class, but after talking to a friend of mine he got me started on the right direction. He told me that I had to use an array and I had to manually keep track of the items in the array.

I can't just insert items into the array at any index, I have to keep it all together and I have to manage the size of the array as well or use any built in functions. Basically, this is going to be the hardest assignment I've done so far. Here is what I have so far:

using System;
using System.Collections;
using System.Collections.Generic;

class MyList : IList
{
    public T[] underlyingArray;
    private int element_count;

    public MyList(int initial_size)
    {
        this.underlyingArray = new T[initial_size];
        this.element_count = 0;
    }

    // TODO Implement: Indexer
    public T this[int index]
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public int Count
    {
        get
        {
            return this.element_count;
        }
    }

    public bool IsReadOnly
    {
        get
        {
            return this.underlyingArray.IsReadOnly;
        }
    }

    // TODO Handle Exception
    public void Add(T item)
    {
        if (element_count < this.underlyingArray.Length)
        {
            this.underlyingArray[element_count] = item;
            this.element_count++;
        }

        else
            throw new IndexOutOfRangeException();
    }

    public void Clear()
    {
        this.element_count = 0;
    }

    public bool Contains(T item)
    {
        for (int index = 0; index < Count; index++)
        {
            if (EqualityComparer.Default.Equals(underlyingArray[index], item));
                return true;
        }
        return false;
    }

    // TODO Implement: Copy
    public void CopyTo(T[] array, int arrayIndex)
    {
        throw new NotImplementedException();
    }

    // TODO Implement: Get Enumerator
    public IEnumerator GetEnumerator()
    {
        throw new NotImplementedException();
    }

    // TODO Implement: Index of
    public int IndexOf(T item)
    {
        throw new NotImplementedException();
    }

    // TODO Implement: Insert
    public void Insert(int index, T item)
    {
        throw new NotImplementedException();
    }

    // TODO Implement: Remove
    public bool Remove(T item)
    {
        throw new NotImplementedException();
    }

    // TODO Implement: Remove at
    public void RemoveAt(int index)
    {
        throw new NotImplementedException();
    }

    // TODO Implement: Get IEnumerable
    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

So far I have only worked on a couple of functions, most importantly the Add function. This function will append an item to the end of the list, but I still haven't figured out how to manage the size of the array on my own.

That's all for now, thanks for reading!

Friday, February 12, 2016

CS 2420 - Assignment 4 - Part 1

Now that we have turned in the last assignment, its time to start on the next one. This time we are switching languages to C#, which hasn't been easy getting used to the new syntax.

The assignment is split in two parts, first I have to rewrite all my sorts that I've done in past assignments but I have to implement an interface on each sort.

So far I have finished most of the sorts and implement the interface on each. Here is my Quick Sort for reference:

class QuickSort : ISorter
{
    public void sort(int[] numbers, int low, int high)
    {
        if (low < high)
        {
            int pivot_location = partition(numbers, low, high);
            sort(numbers, low, pivot_location);
            sort(numbers, pivot_location + 1, high);
        }
    }

    private static int partition(int[] numbers, int low, int high)
    {
        int pivot = numbers[low];
        int wall = low;
        for (int i = low + 1; i < high; i++)
        {
            if (numbers[i] < pivot)
            {
                wall++;
                swap_numbers(numbers, i, wall);
            }
        }
        swap_numbers(numbers, low, wall);
        return wall;
    }

    private static void swap_numbers(int[] numbers, int index1, int index2)
    {
        int temp = numbers[index1];
        numbers[index1] = numbers[index2];
        numbers[index2] = temp;
    }
  
}

I will try to finish this part of the assignment as soon as possible so I can move to the next part. That's all for now, thanks for reading!

Wednesday, February 10, 2016

CS 2420 - Assignment 3

For assignment 3, we had to do two main things: create a linked list and a quicksort.

The Linked List was actually fairly straight forward, but the quicksort gave me the most trouble. Here is my file:

# Christian Munoz
# Assignment 3
import random
import sys
class Node:
"""This class represent a node that will be used in a linked list."""
def __init__(self, data, next=None, previous=None):
self.data = data
self.next = next
self.previous = previous
class LinkedList:
"""This class represents a linked list that will use the Node class above."""
def __init__(self):
self.head = None
self.tail = None
self.length = 0
self.current = None
def insertAfter(self, node, value):
"""Inserts value into a new node after the given node."""
if node is self.tail:
new_node = Node(value, None, node)
self.tail = new_node
else:
new_node = Node(value, node.next, node)
node.next.previous = new_node
node.next = new_node
self.length += 1
def insertBefore(self, node, value):
"""Inserts value into a new node before the given node."""
if node is self.head:
new_node = Node(value, node, None)
self.head = new_node
else:
new_node = Node(value, node, node.previous)
node.previous.next = new_node
node.previous = new_node
self.length += 1
def addFirst(self, value):
"""Adds the given value as the first value in the list."""
new_node = Node(value, self.head, None)
if self.head is not None:
self.head = new_node
self.head.next.previous = new_node
else:
self.head = new_node
self.tail = new_node
self.length += 1
def addLast(self, value):
"""Adds the given value as the last value in the list."""
new_node = Node(value, None, self.tail)
self.tail = new_node
if self.head is None:
self.head = new_node
else:
self.tail.previous.next = new_node
self.length += 1
def find(self, value):
"""Returns the node that contains the given value."""
if self.head is not None:
runner = self.head
while runner is not None:
if runner.data == value:
return runner
runner = runner.next
return None
def remove(self, node):
"""Removes the given node from the list."""
if node is self.head:
self.head = node.next
node.next.previous = None
node.next = None
elif node is self.tail:
self.tail = node.previous
node.previous.next = None
node.previous = None
else:
node.previous.next = node.next
node.next.previous = node.previous
self.length -= 1
def first(self):
"""Returns the first node."""
return self.head
def last(self):
"""Returns the last node."""
return self.tail
def count(self):
"""Returns the number of items in the list."""
return self.length
def __iter__(self):
"""Allows the user to iterate over the values (not the nodes)."""
self.current = self.head
return self
def next(self):
# self.current = self.head
if self.current is not None:
temp = self.current
self.current = self.current.next
return temp.data
else:
raise StopIteration()
def swap_numbers(numbers, index1, index2):
"""This function takes in a list and two indexes to switch them in the list."""
temp = numbers[index1]
numbers[index1] = numbers[index2]
numbers[index2] = temp
def partition(numbers, low, high):
"""This function sets a pivot in the list and compares the values."""
pivot = numbers[low]
wall = low
for i in range(low + 1, high):
if numbers[i] < pivot:
wall += 1
swap_numbers(numbers, i, wall)
swap_numbers(numbers, low, wall)
return wall
def quick_sort(numbers, low, high):
"""This function will perform a quick sort on the list provided."""
if low < high:
pivot_location = partition(numbers, low, high)
quick_sort(numbers, low, pivot_location)
quick_sort(numbers, pivot_location + 1, high)
def main():
"""This is the main function that calls all the other functions."""
# Quicksort section
sorted_list = [1, 2, 3, 4, 5]
reversed_list = [10, 9, 8, 7, 6]
unsorted_list = [11, 15, 19, 12, 13]
oneitem_list = [20]
twoitem_list = [22, 21]
nineitem_list = random.sample(range(1, 50), 9)
thirteenitem_list = random.sample(range(51, 100), 13)
twentyoneitem_list = random.sample(range(1, 99), 21)
print("Lists that will be used with Quicksort:\n")
print("Sorted List:", sorted_list)
print("Reversed List:", reversed_list)
print("Unsorted List:", unsorted_list)
print("One Item List:", oneitem_list)
print("Two Item List:", twoitem_list)
print("Nine Item List:", nineitem_list)
print("Thirteen Item List:", thirteenitem_list)
print("Twenty One Item List:", twentyoneitem_list, '\n')
# Sorting a sorted list
quick_sort(sorted_list, 0, len(sorted_list))
assert sorted_list == [1, 2, 3, 4, 5]
# Sorting a list that is in reverse order
quick_sort(reversed_list, 0, len(reversed_list))
assert reversed_list == [6, 7, 8, 9, 10]
# Sorting an unsorted list
quick_sort(unsorted_list, 0, len(unsorted_list))
assert unsorted_list == [11, 12, 13, 15, 19]
# Sorting a one item list
quick_sort(oneitem_list, 0, len(oneitem_list))
assert oneitem_list == [20]
# Sorting a two item list
quick_sort(twoitem_list, 0, len(twoitem_list))
assert twoitem_list == [21, 22]
# Sorting a random 9 item list
quick_sort(nineitem_list, 0, len(nineitem_list))
for item in range(0, len(nineitem_list)):
if item < len(nineitem_list) - 1:
assert nineitem_list[item] < nineitem_list[item + 1]
# Sorting a random 13 item list
quick_sort(thirteenitem_list, 0, len(thirteenitem_list))
for item in range(0, len(thirteenitem_list)):
if item < len(thirteenitem_list) - 1:
assert thirteenitem_list[item] < thirteenitem_list[item + 1]
# Sorting a random 21 item list
quick_sort(twentyoneitem_list, 0, len(twentyoneitem_list))
for item in range(0, len(twentyoneitem_list)):
if item < len(twentyoneitem_list) - 1:
assert twentyoneitem_list[item] < twentyoneitem_list[item + 1]
print("Lists after Quicksort:\n")
print("Sorted List:", sorted_list)
print("Reversed List:", reversed_list)
print("Unsorted List:", unsorted_list)
print("One Item List:", oneitem_list)
print("Two Item List:", twoitem_list)
print("Nine Item List:", nineitem_list)
print("Thirteen Item List:", thirteenitem_list)
print("Twenty One Item List:", twentyoneitem_list, '\n')
# Linked List section
linked_list = LinkedList()
test_list = [1, 3, 5, 7, 9]
for i in test_list:
linked_list.addLast(i)
# Initial linked list
print("This is the starting Linked List:\n")
default_runner = linked_list.head
while default_runner is not None:
print("Value of Node:", default_runner.data, "Address:", default_runner)
default_runner = default_runner.next
print("Length:", linked_list.count(), "Head:", linked_list.first().data, "Tail:", linked_list.last().data)
# Deleting a couple of nodes
print("\nDeleting 1 and 9 from the list. New list:\n")
linked_list.remove(linked_list.find(1))
linked_list.remove(linked_list.find(9))
delete_runner = linked_list.head
while delete_runner is not None:
print("Value of Node:", delete_runner.data, "Address:", delete_runner)
delete_runner = delete_runner.next
print("Length:", linked_list.count(), "Head:", linked_list.first().data, "Tail:", linked_list.last().data)
# Inserting a couple of node
print("\nInserting 6 at the beginning and 4 at the end. New list:\n")
linked_list.addFirst(6)
linked_list.addLast(4)
add_runner = linked_list.head
while add_runner is not None:
print("Value of Node:", add_runner.data, "Address:", add_runner)
add_runner = add_runner.next
print("Length:", linked_list.count(), "Head:", linked_list.first().data, "Tail:", linked_list.last().data)
# Inserting a couple more nodes
print("\nInserting 2 before 3, inserting 8 after 7. New list: \n")
linked_list.insertBefore(linked_list.find(3), 2)
linked_list.insertAfter(linked_list.find(7), 8)
mod_runner = linked_list.head
while mod_runner is not None:
print("Value of Node:", mod_runner.data, "Address:", mod_runner)
mod_runner = mod_runner.next
print("Length:", linked_list.count(), "Head:", linked_list.first().data, "Tail:", linked_list.last().data)
# Iterate through the list
print("\nIterating through the list:\n")
iter = linked_list.__iter__()
for i in range(linked_list.length):
print("Next value:", iter.next())
if __name__ == "__main__":
main()
sys.exit()
view raw Assignment3.py hosted with ❤ by GitHub

Monday, February 1, 2016

CS 2420 - Assignment 2

For assignment 2, we had to write a couple different sorting algorithms and learn how to use lamdas in our code.

The sorting algorithms gave me the most trouble, but I was able to figure it out. Here is my code:

# Christian Munoz
# Assignment 2
import sys
import random
import math
def swap_numbers(numbers, index1, index2):
"""This function takes in a list and two indexes to switch them in the list."""
temp = numbers[index1]
numbers[index1] = numbers[index2]
numbers[index2] = temp
def bubble_sort(numbers):
"""This function will perform a bubble sort on the given list."""
for start in range(0, len(numbers) - 1):
current_item = 0
for next_item in range(1, len(numbers)):
if numbers[current_item] > numbers[next_item]:
swap_numbers(numbers, current_item, next_item)
current_item += 1
def any(numbers, condition):
"""This function will return True if any number in the list meets
the lambda condition when the function is called."""
for i in numbers:
if condition(i):
return True
def all(numbers, condition):
"""This function will only return True if all the elements in the list meet
the lamda condition when the function is called."""
for i in numbers:
if not condition(i):
return False
return True
def count(numbers, condition):
"""This function returns how many elements in the list satisfy the condition."""
total = 0
for i in numbers:
if condition(i):
total += 1
return total
def genOrdered(elements):
"""This function generates a sequence of random but ordered elements."""
x = 0
for i in range(elements):
x += random.randint(x, x + 7)
yield x
def binarySearch(numbers, element):
"""This function will perform a Binary search."""
low = 0
high = len(numbers) - 1
while (low <= high):
mid = math.floor((low + high) / 2)
if numbers[mid] > element:
high = mid - 1
elif numbers[mid] < element:
low = mid + 1
else:
return mid
def where(numbers, condition):
"""This function returns a sequence of item that satisfies the condition."""
new_list = []
for i in numbers:
if condition(i):
new_list.append(i)
return new_list
def select(numbers, transform):
"""This function converts each item in the sequence using transform."""
new_list = []
for i in numbers:
new_list.append(transform(i))
return new_list
def main():
"""This is the main function that will call all the functions in this file."""
bubble_list = [8, 4, 2, 7, 3, 1]
some_list = [2, 4, 6, 1]
print("Before bubble sort: ", bubble_list)
bubble_sort(bubble_list)
print("After bubble sort: ", bubble_list, '\n')
print("This is the list that will be use for the lambda functions:", some_list)
print("Are ANY of the numbers on the list greater than 0?", any(some_list, lambda x: x >= 0))
print("Are ALL the numbers on the list divisible by 2?", all(some_list, lambda x: x % 2 == 0))
print("How many numbers on the list are divisible by 2?", count(some_list, lambda x: x % 2 == 0), '\n')
# Create the generator object
generator = genOrdered(5)
print("A list of random but ordered numbers:")
for i in generator:
print(i)
print("")
print("Binary list:", bubble_list)
print("The index of 8 is:", binarySearch(bubble_list, 8), '\n')
print("List used for the WHERE and SELECT functions:", bubble_list)
print("List of numbers divisible by 4:", where(bubble_list, lambda x: x % 4 == 0))
print("List of the numbers multiplied by 2:", select(bubble_list, lambda x: 2*x))
if __name__ == "__main__":
main()
sys.exit()
view raw Assignment2.py hosted with ❤ by GitHub