From 50de92ec151c5836dffa45181cad1da4e7cfed7b Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Sun, 11 Aug 2013 17:36:45 +0300 Subject: [PATCH 01/19] Delete README.md --- README.md | 247 ------------------------------------------------------ 1 file changed, 247 deletions(-) delete mode 100644 README.md diff --git a/README.md b/README.md deleted file mode 100644 index fefc3ff58..000000000 --- a/README.md +++ /dev/null @@ -1,247 +0,0 @@ -Mega Project List -======== - -A list of practical projects that anyone can solve in any programming language (See [solutions](https://github.com/thekarangoel/Projects-Solutions)). These projects are divided in multiple categories, and each category has it's own folder. - -#### [RECOGNITION](https://github.com/thekarangoel/Projects/tree/master/RECOGNITION) - -Ever since this repo was created, it has been in the top list on GH. Be it the daily or weekly list! This repo is in the top 5 on GitHub on [July 14 2013](https://raw.github.com/thekarangoel/Projects/master/RECOGNITION/top5-2013-07-14.png). (And again on [July 22, 2013](https://raw.github.com/thekarangoel/Projects/master/RECOGNITION/top5-2013-07-22%2013_10_30.png), and again on [July 23, 2013](https://raw.github.com/thekarangoel/Projects/master/RECOGNITION/top5-2013-07-23.png).) And on [weekly](https://raw.github.com/thekarangoel/Projects/master/RECOGNITION/top5-weekly-2013-07-22.png) [list](https://github.com/thekarangoel/Projects/blob/master/RECOGNITION/top5-weekly-2013-07-23.png) during the week of July 2013. In the last week of July, *Projects* was in the monthly top list on GH. - -![July 25, 2013](https://raw.github.com/thekarangoel/Projects/master/RECOGNITION/top5-monthly-2013-07-25.png) - -=============================== - -### [CONTRIBUTING](https://github.com/thekarangoel/Projects/blob/master/CONTRIBUTING.md) - -See ways of [contributing](https://github.com/thekarangoel/Projects/blob/master/CONTRIBUTING.md) to this repo. You can contribute solutions (will be published in this [repo](https://github.com/thekarangoel/Projects-Solutions)) to existing problems, add new projects or remove existing ones. Make sure you follow all instructions properly. - -================================ - -### [Solutions](https://github.com/thekarangoel/Projects-Solutions) - -You can find implementations of these projects in many other languages by other users in this [repo](https://github.com/thekarangoel/Projects-Solutions). - -================================ - -Some details about this repo: - -* I will use Python to solve these. Why? Because I want to learn the language quickly. -* I have no interest in making games, so I'm excluding those from the list below. -* I'm not interested in networking, so I *might* skip all (or some) of them. -* The projects will not be made in the order posted. -* I may not be able to complete all of them. -* My method of solving them may not be the best. If you do not like my algorithm(s), please add a comment for the file/commit or open an issue, and I'll try to improve. - -I will link to each project that I complete. Some will be in this same repo, some bigger ones will have dedicated repos. - -To get started, fork this repo, delete this README and rename [*README-scratch.md*](https://github.com/thekarangoel/Projects/blob/master/README-scratch.md) to *README.md*. - -=============================== - -Numbers ---------- - -[**Find PI to the Nth Digit**](https://github.com/thekarangoel/Projects/blob/master/Numbers/pi.py) - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. - -[**Fibonacci Sequence**](https://github.com/thekarangoel/Projects/blob/master/Numbers/fibonacci.py) - Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number. - -[**Prime Factorization**](https://github.com/thekarangoel/Projects/blob/master/Numbers/prime.py) - Have the user enter a number and find all Prime Factors (if there are any) and display them. - -[**Next Prime Number**](https://github.com/thekarangoel/Projects/blob/master/Numbers/next_prime.py) - Have the program find prime numbers until the user chooses to stop asking for the next one. - -[**Find Cost of Tile to Cover W x H Floor**](https://github.com/thekarangoel/Projects/blob/master/Numbers/tile.py) - Calculate the total cost of tile it would take to cover a floor plan of width and height, using a cost entered by the user. - -**Mortgage Calculator** - Calculate the monthly payments of a fixed term mortgage over given Nth terms at a given interest rate. Also figure out how long it will take the user to pay back the loan. - -[**Change Return Program**](https://github.com/thekarangoel/Projects/blob/master/Numbers/change.py) - The user enters a cost and then the amount of money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change. - -[**Binary to Decimal and Back Converter**](https://github.com/thekarangoel/Projects/blob/master/Numbers/binary_decimal.py) - Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent. - -[**Calculator**](https://github.com/thekarangoel/Projects/blob/master/Numbers/calc.py) - A simple calculator to do basic operators. Make it a scientific calculator for added complexity. - -**Unit Converter (temp, currency, volume, mass and more)** - Converts various units between one another. The user enters the type of unit being entered, the type of unit they want to convert to and then the value. The program will then make the conversion. - -[**Alarm Clock**](https://github.com/thekarangoel/Projects/blob/master/Numbers/alarm.py) - A simple clock where it plays a sound after X number of minutes/seconds or at a particular time. - -[**Distance Between Two Cities**](https://github.com/thekarangoel/Projects/blob/master/Numbers/distance.py) - Calculates the distance between two cities and allows the user to specify a unit of distance. This program may require finding coordinates for the cities like latitude and longitude. - -[**Credit Card Validator**](https://github.com/thekarangoel/Projects/blob/master/Numbers/credit_card_validator.py) - Takes in a credit card number from a common credit card vendor (Visa, MasterCard, American Express, Discoverer) and validates it to make sure that it is a valid number (look into how credit cards use a checksum). - -**Tax Calculator** - Asks the user to enter a cost and either a country or state tax. It then returns the tax plus the total cost with tax. - -[**Factorial Finder**](https://github.com/thekarangoel/Projects/blob/master/Numbers/factorial.py) - The Factorial of a positive integer, n, is defined as the product of the sequence n, n-1, n-2, ...1 and the factorial of zero, 0, is defined as being 1. Solve this using both loops and recursion. - -**Complex Number Algebra** - Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. - -[**Happy Numbers**](https://github.com/thekarangoel/Projects/blob/master/Numbers/happy_numbers.py) - A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Take an input number from user, and find first 8 happy numbers from that input. - -**Number Names** - Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). *Optional: Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers).* - -Graphs ---------- - -**Graph from links** - Create a program that will create a graph or network from a series of links. - -**Eulerian Path** - Create a program which will take as an input a graph and output either a Eulerian path or a Eulerian cycle, or state that it is not possible. A Eulerian Path starts at one node and traverses every edge of a graph through every node and finishes at another node. A Eulerian cycle is a eulerian Path that starts and finishes at the same node. - -**Connected Graph** - Create a program which takes a graph as an input and outputs whether every node is connected or not. - -**Dijkstra’s Algorithm** - Create a program that finds the shortest path through a graph using its edges. - -Text ---------- - -[**Reverse a String**](https://github.com/thekarangoel/Projects/blob/master/Text/reverse.py) - Enter a string and the program will reverse it and print it out. - -[**Pig Latin**](https://github.com/thekarangoel/Projects/blob/master/Text/piglatin.py) - Pig Latin is a game of alterations played on the English language game. To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word and an ay is affixed (Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules. - -[**Count Vowels**](https://github.com/thekarangoel/Projects/blob/master/Text/count_vowels.py) - Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found. - -[**Check if Palindrome**](https://github.com/thekarangoel/Projects/blob/master/Text/palindrome.py) - Checks if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like “racecar” - -[**Count Words in a String**](https://github.com/thekarangoel/Projects/blob/master/Text/count_words.py) - Counts the number of individual words in a string and display the top 5/10 most used words. - -**Text Editor** - Notepad style application that can open, edit, and save text documents. *Optional: Add syntax highlighting and other features.* - -**RSS Feed Creator** - Given a link to RSS/Atom Feed, get all posts and display them. - -**Post it Notes Program** - A program where you can add text reminders and post them. *Optional: You can have the program also add popup reminders.* - -**Quote Tracker (market symbols etc)** - A program which can go out and check the current value of stocks for a list of symbols entered by the user. The user can set how often the stocks are checked. For CLI, show whether the stock has moved up or down. *Optional: If GUI, the program can show green up and red down arrows to show which direction the stock value has moved.* - -**Guestbook / Journal** - A simple application that allows people to add comments or write journal entries. It can allow comments or not and timestamps for all entries. Could also be made into a shout box. *Optional: Deploy it on Google App Engine or Heroku or any other PaaS (if possible, of course).* - -**Fortune Teller (Horoscope)** - A program that checks your horoscope on various astrology sites and puts them together for you each day. - -**Vigenere / Vernam / Ceasar Ciphers** - Functions for encrypting and decrypting data messages. Then send them to a friend. - -**Random Gift Suggestions** - Enter various gifts for certain people when you think of them. When its time to give them a gift (xmas, birthday, anniversary) it will randomly pick one. *Optional: Suggest places you can get it (link to Amazon page?).* - -**Markdown to HTML Converter** - Converts Markdown formatted text into HTML files. Implement basic tags like `p`, `strong`, `em` etc. *Optional: Implement all tags from [Markdown Syntax Docs](daringfireball.net/projects/markdown/syntax).* - -**Regex Query Tool** - A tool that allows the user to enter a text string and then in a separate control enter a regex pattern. It will run the regular expression against the source text and return any matches or flag errors in the regular expression. - -Networking ---------- - -**FTP Program** - A file transfer program which can transfer files back and forth from a remote web sever. - -**Bandwidth Monitor** - A small utility program that tracks how much data you have uploaded and downloaded from the net during the course of your current online session. See if you can find out what periods of the day you use more and less and generate a report or graph that shows it. - -**Port Scanner** - Enter an IP address and a port range where the program will then attempt to find open ports on the given computer by connecting to each of them. On any successful connections mark the port as open. - -**Mail Checker (POP3 / IMAP)** - The user enters various account information include web server and IP, protocol type (POP3 or IMAP) and the application will check for email at a given interval. - -**Country from IP Lookup** - Enter an IP address and find the country that IP is registered in. *Optional: Find the Ip automatically.* - -**Whois Search Tool** - Enter an IP or host address and have it look it up through whois and return the results to you. - -**Site Checker with Time Scheduling** - An application that attempts to connect to a website or server every so many minutes or a given time and check if it is up. If it is down, it will notify you by email or by posting a notice on screen. - -Classes ---------- - -[**Product Inventory Project**](https://github.com/thekarangoel/Projects/blob/master/Classes/product_inventory.py) - Create an application which manages an inventory of products. Create a product class which has a price, id, and quantity on hand. Then create an *inventory* class which keeps track of various products and can sum up the inventory value. - -**Airline / Hotel Reservation System** - Create a reservation system which books airline seats or hotel rooms. It charges various rates for particular sections of the plane or hotel. Example, first class is going to cost more than coach. Hotel rooms have penthouse suites which cost more. Keep track of when rooms will be available and can be scheduled. - -**Bank Account Manager** - Create a class called Account which will be an abstract class for three other classes called CheckingAccount, SavingsAccount and BusinessAccount. Manage credits and debits from these accounts through an ATM style program. - -**Patient / Doctor Scheduler** - Create a patient class and a doctor class. Have a doctor that can handle multiple patients and setup a scheduling program where a doctor can only handle 16 patients during an 8 hr work day. - -**Recipe Creator and Manager** - Create a recipe class with ingredients and a put them in a recipe manager program that organizes them into categories like deserts, main courses or by ingredients like chicken, beef, soups, pies etc. - -**Image Gallery** - Create an image abstract class and then a class that inherits from it for each image type. Put them in a program which displays them in a gallery style format for viewing. - -**Shape Area and Perimeter Classes** - Create an abstract class called Shape and then inherit from it other shapes like diamond, rectangle, circle, triangle etc. Then have each class override the area and perimeter functionality to handle each shape type. - -**Flower Shop Ordering To Go** - Create a flower shop application which deals in flower objects and use those flower objects in a bouquet object which can then be sold. Keep track of the number of objects and when you may need to order more. - -**Family Tree Creator** - Create a class called Person which will have a name, when they were born and when (and if) they died. Allow the user to create these Person classes and put them into a family tree structure. Print out the tree to the screen. - -Threading ---------- - -**Create A Progress Bar for Downloads** - Create a progress bar for applications that can keep track of a download in progress. The progress bar will be on a separate thread and will communicate with the main thread using delegates. - -**Bulk Thumbnail Creator** - Picture processing can take a bit of time for some transformations. Especially if the image is large. Create an image program which can take hundreds of images and converts them to a specified size in the background thread while you do other things. For added complexity, have one thread handling re-sizing, have another bulk renaming of thumbnails etc. - -Web ---------- - -[**Page Scraper**](https://github.com/thekarangoel/Projects/blob/master/Web/page_scraper.py) - Create an application which connects to a site and pulls out all links, or images, and saves them to a list. *Optional: Organize the indexed content and don’t allow duplicates. Have it put the results into an easily searchable index file.* - -**Web Browser with Tabs** - Create a small web browser that allows you to navigate the web and contains tabs which can be used to navigate to multiple web pages at once. For simplicity don’t worry about executing Javascript or other client side code. - -**Online White Board** - Create an application which allows you to draw pictures, write notes and use various colors to flesh out ideas for projects. *Optional: Add feature to invite friends to collaborate on a white board online.* - -**Get Atomic Time from Internet Clock** - This program will get the true atomic time from an atomic time clock on the Internet. Use any one of the atomic clocks returned by a simple Google search. - -**Fetch Current Weather** - Get the current weather for a given zip/postal code. *Optional: Try locating the user automatically.* - -**Scheduled Auto Login and Action** - Make an application which logs into a given site on a schedule and invokes a certain action and then logs out. This can be useful for checking web mail, posting regular content, or getting info for other applications and saving it to your computer. - -**E-Card Generator** - Make a site that allows people to generate their own little e-cards and send them to other people. Do not use Flash. Use a picture library and perhaps insightful mottos or quotes. - -**Content Management System** - Create a content management system (CMS) like Joomla, Drupal, PHP Nuke etc. Start small. *Optional: Allow for the addition of modules/addons.* - -**Web Board (Forum)** - Create a forum for you and your buddies to post, administer and share thoughts and ideas. - -**CAPTCHA Maker** - Ever see those images with letters a numbers when you signup for a service and then asks you to enter what you see? It keeps web bots from automatically signing up and spamming. Try creating one yourself for online forms. - -Files ---------- - -**Quiz Maker** - Make an application which takes various questions form a file, picked randomly, and puts together a quiz for students. Each quiz can be different and then reads a key to grade the quizzes. - -**File Explorer** - Create your own simple windows explorer program. Add feature(s) you always thought are missing from MS Windows Explorer or Mac Finder. - -**Sort Excel/CSV File Utility** - Reads a file of records, sorts them, and then writes them back to the file. Allow the user to choose various sort style and sorting based on a particular field. - -**Create Zip File Maker** - The user enters various files from different directories and the program zips them up into a zip file. *Optional: Apply actual compression to the files. Start with Huffman Algorithm.* - -**PDF Generator** - An application which can read in a text file, html file or some other file and generates a PDF file out of it. Great for a web based service where the user uploads the file and the program returns a PDF of the file. *Optional: Deploy on GAE or Heroku if possible.* - -**Mp3 Tagger** - Modify and add ID3v1 tags to MP3 files. See if you can also add in the album art into the MP3 file’s header as well as other ID3v2 tags. - -**Code Snippet Manager** - Another utility program that allows coders to put in functions, classes or other tidbits to save for use later. Organized by the type of snippet or language the coder can quickly look up code. *Optional: For extra practice try adding syntax highlighting based on the language.* - -Databases ---------- - -**SQL Query Analyzer** - A utility application which a user can enter a query and have it run against a local database and look for ways to make it more efficient. - -**Remote SQL Tool** - A utility that can execute queries on remote servers from your local computer across the Internet. It should take in a remote host, user name and password, run the query and return the results. - -**Report Generator** - Create a utility that generates a report based on some tables in a database. Generates a sales reports based on the order/order details tables or sums up the days current database activity. - -**Event Scheduler and Calendar** - Make an application which allows the user to enter a date and time of an event, event notes and then schedule those events on a calendar. The user can then browse the calendar or search the calendar for specific events. *Optional: Allow the application to create re-occurrence events that reoccur every day, week, month, year etc.* - -**Budget Tracker** - Write an application that keeps track of a household’s budget. The user can add expenses, income, and recurring costs to find out how much they are saving or losing over a period of time. *Optional: Allow the user to specify a date range and see the net flow of money in and out of the house budget for that time period.* - -**Address Book** - Keep track of various contacts, their numbers, emails and little notes about them like a Rolodex in the database. - -**TV Show Tracker** - Got a favorite show you don’t want to miss? Don’t have a PVR or want to be able to find the show to then PVR it later? Make an application which can search various online TV Guide sites, locate the shows/times/channels and add them to a database application. The database/website then can send you email reminders that a show is about to start and which channel it will be on. - -**Travel Planner System** - Make a system that allows users to put together their own little travel itinerary and keep track of the airline / hotel arrangements, points of interest, budget and schedule. - -Graphics and Multimedia ---------- - -**Slide Show** - Make an application that shows various pictures in a slide show format. *Optional: Try adding various effects like fade in/out, star wipe and window blinds transitions.* - -**Stream Video from Online** - Try to create your own online streaming video player. - -**Mp3 Player** - A simple program for playing your favorite music files. Add features you though are missing from your favorite music player. - -**Watermarking Application** - Have some pictures you want copyright protected? Add your own logo or text lightly across the background so that no one can simply steal your graphics off your site. Make a program that will add this watermark to the picture. *Optional: Use threading to process multiple images simultaneously.* - -**Turtle Graphics** - This is a common project where you create a floor of 20 x 20 squares. Using various commands you tell a turtle to draw a line on the floor. You have move forward, left or right, lift or drop pen etc. Do a search online for "Turtle Graphics" for more information. *Optional: Allow the program to read in the list of commands from a file.* - -=============================================== - -Sources -======= - -[Martyr2’s Mega Project List](http://www.dreamincode.net/forums/topic/78802-martyr2s-mega-project-ideas-list/) -[Rosetta Code](http://rosettacode.org/) From 0a44172f1deeb68966faae72977e6234519cd97b Mon Sep 17 00:00:00 2001 From: Roman Gotsiy Date: Sun, 11 Aug 2013 19:21:41 +0300 Subject: [PATCH 02/19] Removed Karan's python scripts --- Classes/product_inventory.py | 78 -------------------------------- Numbers/alarm.py | 49 -------------------- Numbers/binary_decimal.py | 50 -------------------- Numbers/calc.py | 22 --------- Numbers/change.py | 43 ------------------ Numbers/credit_card_validator.py | 41 ----------------- Numbers/distance.py | 55 ---------------------- Numbers/factorial.py | 33 -------------- Numbers/fibonacci.py | 15 ------ Numbers/happy_numbers.py | 40 ---------------- Numbers/next_prime.py | 25 ---------- Numbers/pi.py | 10 ---- Numbers/prime.py | 24 ---------- Numbers/tile.py | 11 ----- README-scratch.md => README.md | 0 Text/count_vowels.py | 19 -------- Text/count_words.py | 26 ----------- Text/palindrome.py | 12 ----- Text/piglatin.py | 22 --------- Text/reverse.py | 8 ---- Web/page_scraper.py | 33 -------------- 21 files changed, 616 deletions(-) delete mode 100644 Classes/product_inventory.py delete mode 100644 Numbers/alarm.py delete mode 100644 Numbers/binary_decimal.py delete mode 100644 Numbers/calc.py delete mode 100644 Numbers/change.py delete mode 100644 Numbers/credit_card_validator.py delete mode 100644 Numbers/distance.py delete mode 100644 Numbers/factorial.py delete mode 100644 Numbers/fibonacci.py delete mode 100644 Numbers/happy_numbers.py delete mode 100644 Numbers/next_prime.py delete mode 100644 Numbers/pi.py delete mode 100644 Numbers/prime.py delete mode 100644 Numbers/tile.py rename README-scratch.md => README.md (100%) delete mode 100644 Text/count_vowels.py delete mode 100644 Text/count_words.py delete mode 100644 Text/palindrome.py delete mode 100644 Text/piglatin.py delete mode 100644 Text/reverse.py delete mode 100644 Web/page_scraper.py diff --git a/Classes/product_inventory.py b/Classes/product_inventory.py deleted file mode 100644 index e337a7d5e..000000000 --- a/Classes/product_inventory.py +++ /dev/null @@ -1,78 +0,0 @@ -""" -Product Inventory Project - Create an application which manages -an inventory of products. Create a product class which has a -price, id, and quantity on hand. Then create an inventory class -which keeps track of various products and can sum up the inventory -value. -""" - -class Product: - - def __init__(self, price, pid, qty): - """ - Class constructor that needs a price, a product id, - and quantity. - """ - self.price = price - self.pid = pid - self.qty = qty - - def update_qty(self, qty, method='add'): - """ - Updates the quantity of produts. By default, adds the - passed quantity. Pass method as 'subtract' to subtract - the quantity. - """ - if method == 'add': - self.qty += qty - elif method == 'subtract': - self.qty = max(0, self.qty - qty) - - def print_product(self): - """ - Prints a single product. - """ - print '%d\t%s\t%.02f each' % (self.pid, self.qty, self.price) - -class Inventory: - - def __init__(self): - """ - Initializes the class instance. - """ - self.products = [] # list to hold all products - - def add(self, product): - """ - Adds a passed Product to the list of products. - """ - self.products.append(product) - - def print_inventory(self): - """ - Prints the current inventory, and the total value - of products. - """ - value = 0 - for product in self.products: - print '%d\t%s\t%.02f each' % (product.pid, product.qty, product.price) - value += (product.price * product.qty) - print '\nTotal value: %.02f' % value - -if __name__ == '__main__': - p1 = Product(1.4, 123, 5) - p2 = Product(1, 3432, 100) - p3 = Product(100.4, 2342, 99) - - - i = Inventory() - i.add(p1) - i.add(p2) - i.add(p3) - i.print_inventory() - - p1.update_qty(10) - i.print_inventory() - - p1.update_qty(10, method='subtract') - i.print_inventory() diff --git a/Numbers/alarm.py b/Numbers/alarm.py deleted file mode 100644 index a0a1c7367..000000000 --- a/Numbers/alarm.py +++ /dev/null @@ -1,49 +0,0 @@ -""" -Alarm Clock - A simple clock where it plays a sound after -X number of minutes/seconds or at a particular time. - -Dependencies: -pyglet - pip install pyglet -""" - -import time -import winsound -import pyglet - -def play(hh, mm): - not_alarmed = 1 - - while(not_alarmed): - cur_time = list(time.localtime()) # get the time right now - hour = cur_time[3] # find the hour - minute = cur_time[4] # and the minute - if hour == hh and minute == mm: - song = pyglet.media.load('bin/sound.wav') - song.play() # play the sound - pyglet.app.run() - not_alarmed = 0 # stop the loop - -if __name__ == '__main__': - - print """ - 1. Play sound after X minutes - 2. Play sound at an exact time - """ - choice = input('What do you want to do? ') - - if choice == 1: - mins = input('How many minutes from now? ') - hh_from_now = mins / 60 # if minutes > 60, this will adjust the hours - mm_from_now = mins % 60 # and then the minutes - cur_time = list(time.localtime()) # get the time right now - hour = cur_time[3] # find the current hour - minute = cur_time[4] # and the current minute - hh = (hour + hh_from_now) % 24 # cycle through the clock if hh > 24 - mm = (minute + mm_from_now) % 60 # cycle through the clock if mm > 60 - play(hh, mm) - elif choice == 2: - hh = input('What hour do you want to wake up (0-23)? ') - mm = input('What minute do you want to wake up (0-59)? ') - play(hh, mm) - diff --git a/Numbers/binary_decimal.py b/Numbers/binary_decimal.py deleted file mode 100644 index f378fb76f..000000000 --- a/Numbers/binary_decimal.py +++ /dev/null @@ -1,50 +0,0 @@ -""" -Binary to Decimal and Back Converter -Develop a converter to convert a decimal number to binary -or a binary number to its decimal equivalent. -""" - -def binary_to_decimal(binary): - """ - Converts a binary number into a decimal number. - """ - decimal = 0 - index = 0 - while binary > 0: - last = binary % 10 - binary = binary / 10 - decimal += (last * (2 ** index)) - index += 1 - return decimal - -def decimal_to_binary(decimal): - """ - Converts a decimal number into a binary number. - """ - binary = "" - remainders = [] - while decimal > 0: - remainders.append(str(decimal % 2)) - decimal /= 2 - remainders.reverse() - binary = "".join(remainders) - return binary - -if __name__ == '__main__': - print """ - 1. Binary to Decimal - 2. Decimal to Binary\n - """ - - choice = input("Make a choice: ") - - if choice == 1: - binary = input("Binary to convert: ") - print "The binary number %d in decimal is %d" % \ - (binary, binary_to_decimal(binary)) - elif choice == 2: - decimal = input("Decimal to convert: ") - print "The decimal number %d in binary is %s" % \ - (decimal, decimal_to_binary(decimal)) - else: - print "Invalid choice" diff --git a/Numbers/calc.py b/Numbers/calc.py deleted file mode 100644 index 9daf8371e..000000000 --- a/Numbers/calc.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: cp1252 -*- -""" -Calculator - A simple calculator to do basic operators. -""" - -if __name__ == '__main__': - num1 = input("Number 1: ") - num2 = input("Number 2: ") - op = raw_input("Operation (+, -, /, *): ") - - if op not in '+-/*': - print "Invalid operator" - else: - if op == '+': - res = num1 + num2 - elif op == '-': - res = num1 - num2 - elif op == '/': - res = num1 / num2 - elif op == '*': - res = num1 * num2 - print "%d %s %d = %d" % (num1, op, num2, res) diff --git a/Numbers/change.py b/Numbers/change.py deleted file mode 100644 index 6d6f13cde..000000000 --- a/Numbers/change.py +++ /dev/null @@ -1,43 +0,0 @@ -# Change Return Program - The user enters a cost and -# then the amount of money given. The program will figure -# out the change and the number of quarters, dimes, nickels, -# pennies needed for the change. - -if __name__ == '__main__': - cost = input("What's the cost in dollars? ") - given = input("What's the amount of dollars given? ") - - change = given - cost - - print "\n" - if change < 0: - print "Please ask for $%.2f more from the customer." % (-change) # double negation - else: - print "The change is $%.2f." % change - - q = 0 # 0.25 - d = 0 # 0.10 - n = 0 # 0.05 - p = 0 # 0.01 - - change = int(change * 100) # let's talk about cents - - if change >= 25: - q = int(change / 25) - change = change % 25 - if change >= 10: - d = int(change / 10) - change = change % 10 - if change >= 5: - n = int(change / 5) - change = change % 5 - if change >= 1: - p = change # rest all change is in pennies - - print "Give the following change to the customer:" - print "Quarters: %d\tDimes: %d\tNickels: %d\tPennies: %d" \ - % (q, d, n, p) - - # DEBUG - # print "Total change per the number of coins is %.2f" % \ - # ((q * .25) + (d * .10) + (n * 0.05) + (p * 0.01)) diff --git a/Numbers/credit_card_validator.py b/Numbers/credit_card_validator.py deleted file mode 100644 index 7bb0a39cf..000000000 --- a/Numbers/credit_card_validator.py +++ /dev/null @@ -1,41 +0,0 @@ -""" -Credit Card Validator - Takes in a credit card number from a -common credit card vendor (Visa, MasterCard, American Express, -Discoverer) and validates it to make sure that it is a valid -number (look into how credit cards use a checksum). - -This program works with *most* credit card numbers. - -Uses Luhn Algorithm (http://en.wikipedia.org/wiki/Luhn_algorithm). - -1. From the rightmost digit, which is the check digit, moving -left, double the value of every second digit; if product of this -doubling operation is greater than 9 (e.g., 7 * 2 = 14), then -sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5). - -2. Add together doubled digits with the undoubled digits from the -original number. - -3. If the total modulo 10 is equal to 0 (if the total ends in zero) -then the number is valid according to the Luhn formula; else it is -not valid. -""" - -if __name__ == '__main__': - number = raw_input('Enter the credit card number of check: ').replace(' ', '') - #if not number.isdigit(): - # raise Exception('Invalid credit card number. Make sure it\'s all digits (with optional spaces in between).' - - digits = [int(char) for char in number] - - # double alternate digits (step 1) - doubled = [(digit * 2) if (i % 2 == 0) else digit \ - for (i, digit) in enumerate(digits)] # i <3 python - # sum digits of number > 10 (step 2) - summed = [num if num < 10 else sum([int(dig) for dig in str(num)]) \ - for num in doubled] # i <3 python ** 2 - # step 3 - if sum(summed) % 10 == 0: - print 'The number is valid' - else: - print 'The number is invalid' diff --git a/Numbers/distance.py b/Numbers/distance.py deleted file mode 100644 index 65cfc9a9b..000000000 --- a/Numbers/distance.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python - -""" -Distance Between Two Cities - Calculates the distance between -two cities and allows the user to specify a unit of distance. -This program may require finding coordinates for the cities -like latitude and longitude. - -Uses the Haversine formula -(http://www.movable-type.co.uk/scripts/latlong.html) - -Dependencies: -geopy - pip install geopy -""" - -from geopy import geocoders # to find lat/lon for the city -import math - -R = 6373 # km - -city1 = raw_input('Enter city 1: ') -city2 = raw_input('Enter city 2: ') -unit = raw_input('Enter unit of distance (Enter "K" for KM or "M" for MI): ').lower() - -if unit in 'km': - - g = geocoders.GoogleV3() - - try: - city1, (lat1, lon1) = g.geocode(city1) - city2, (lat2, lon2) = g.geocode(city2) - except: - raise Exception('Unable to locate the citites. Check the city names.') - - # convert decimal locations to radians - lat1 = math.radians(lat1) - lon1 = math.radians(lon1) - lat2 = math.radians(lat2) - lon2 = math.radians(lon2) - - # start haversne formula - dlon = lon2 - lon1 - dlat = lat2 - lat1 - a = (math.sin(dlat/2) ** 2) + math.cos(lat1) * math.cos(lat2) * \ - (math.sin(dlon/2) ** 2) - c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) - d = R * c - - if unit == 'k': - print 'Distance between %s and %s is %.04f km' % (city1, city2, d) - else: - print 'Distance between %s and %s is %.04f mi' % (city1, city2, d / 1.60934) -else: - print 'Invalid unit input!' diff --git a/Numbers/factorial.py b/Numbers/factorial.py deleted file mode 100644 index b09d5e2f4..000000000 --- a/Numbers/factorial.py +++ /dev/null @@ -1,33 +0,0 @@ -""" -Factorial Finder - The Factorial of a positive integer, n, -is defined as the product of the sequence n, n-1, n-2, ...1 -and the factorial of zero, 0, is defined as being 1. Solve -this using both loops and recursion. -""" - -def fact_loop(n): - """ - Returns the factorial of a given positive, non-zero integer - using loops. - """ - fact = 1 - while n > 0: - fact *= n - n -= 1 - return fact - -def fact_recursion(n): - """ - Returns the factorial of a given positive, non-zero integer - using recursion. - """ - return 1 if n == 0 else n * fact_recursion(n - 1) # if user as ternary operator - -if __name__ == '__main__': - n = input('Enter a positive number: ') - - if n >= 0: - print 'Factorial of %d by loops is %d' % (n, fact_loop(n)) - print 'Factorial of %d by recursion is %d' % (n, fact_recursion(n)) - else: - print 'Not a valid number' diff --git a/Numbers/fibonacci.py b/Numbers/fibonacci.py deleted file mode 100644 index a6692a94f..000000000 --- a/Numbers/fibonacci.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: cp1252 -*- -# Fibonacci Sequence - Enter a number and have the -# program generate the Fibonacci sequence to that number -# or to the Nth number - -n = int(raw_input('How many numbers do you need? ')) -series = [1] - -while len(series) < n: - if len(series) == 1: - series.append(1) - else: - series.append(series[-1] + series[-2]) - -print series diff --git a/Numbers/happy_numbers.py b/Numbers/happy_numbers.py deleted file mode 100644 index a50f05f92..000000000 --- a/Numbers/happy_numbers.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -Happy Numbers - A happy number is defined by the -following process. Starting with any positive integer, -replace the number by the sum of the squares of its -digits, and repeat the process until the number equals -1 (where it will stay), or it loops endlessly in a -cycle which does not include 1. Those numbers for which -this process ends in 1 are happy numbers, while those -that do not end in 1 are unhappy numbers. Take an input -number from user, and find first 8 happy numbers from -that input. -""" - -NUMBERS_REQUIRED = 8 # number of happy numbers required - -def is_happy_number(num): - seen = [] - while True: - sum_digits = sum(int(digit) ** 2 for digit in str(num)) - if sum_digits == 1: - return True - elif sum_digits in seen: - return False - else: - num = sum_digits - seen.append(num) - -if __name__ == '__main__': - - happies = [] # list of happy numbers found - - num = input('Start at: ') - - while len(happies) != NUMBERS_REQUIRED: - if is_happy_number(num): - happies.append(num) - num += 1 - - print happies - diff --git a/Numbers/next_prime.py b/Numbers/next_prime.py deleted file mode 100644 index 0f356acee..000000000 --- a/Numbers/next_prime.py +++ /dev/null @@ -1,25 +0,0 @@ -# Next Prime Number - Have the program find prime -# numbers until the user chooses to stop asking for -# the next one. - -def next_prime(current): - next_prime = current + 1 # start checking for primes 1 number after the current one - i = 2 - while next_prime > i: # check with numbers up to next_prime - 1 - if next_prime % i == 0: # if number is divisible - next_prime += 1 # ready to check the next number - i = 2 # reset i to check divisibility again from 2 - else: - i += 1 # increment the divisor - return next_prime - -if __name__ == '__main__': - current_prime = 2 - while True: - response = raw_input('Do you want the next prime? (Y/N) ') - - if response.lower().startswith('y'): - print current_prime - current_prime = next_prime(current_prime) - else: - break diff --git a/Numbers/pi.py b/Numbers/pi.py deleted file mode 100644 index 559480110..000000000 --- a/Numbers/pi.py +++ /dev/null @@ -1,10 +0,0 @@ -# Find PI to the Nth Digit - -from math import * - -digits = raw_input('Enter number of digits to round PI to: ') - -# print ('{0:.%df}' % min(20, int(digits))).format(math.pi) # nested string formatting - -# calculate pi using Machin-like Formula -print ('{0:.%df}' % min(30, int(digits))).format(4 * (4 * atan(1.0/5.0) - atan(1.0/239.0))) diff --git a/Numbers/prime.py b/Numbers/prime.py deleted file mode 100644 index 45cbe1390..000000000 --- a/Numbers/prime.py +++ /dev/null @@ -1,24 +0,0 @@ -# Prime Factorization - Have the user enter a number -# and find all Prime Factors (if there are any) and -# display them. - -import math - -def is_a_prime(x): - for i in range(2, x): - if x % i == 0: - return False - return True - -# standard boilerplate -if __name__ == '__main__': - n = int(raw_input('Enter the number to find prime factors of: ')) - - factors = [] - - for i in range(2, n + 1): - while n % i == 0: # Thanks @madsulrik - if is_a_prime(i): - factors.append(i) - n /= i - print factors diff --git a/Numbers/tile.py b/Numbers/tile.py deleted file mode 100644 index 6f4d7cf62..000000000 --- a/Numbers/tile.py +++ /dev/null @@ -1,11 +0,0 @@ -# Find Cost of Tile to Cover W x H Floor - Calculate -# the total cost of tile it would take to cover a floor -# plan of width and height, using a cost entered by the user. - -# Use input as the input can be integer and float -cost = input("What's the cost per sq. feet? ") -width = input("What's the width of the floor? ") -height = input("What's the height of the floor? ") - -print "The total cost is $%.2f for %.2f square feet" \ - % (width * height * cost, width * height) diff --git a/README-scratch.md b/README.md similarity index 100% rename from README-scratch.md rename to README.md diff --git a/Text/count_vowels.py b/Text/count_vowels.py deleted file mode 100644 index fe55626f1..000000000 --- a/Text/count_vowels.py +++ /dev/null @@ -1,19 +0,0 @@ -""" -Count Vowels - Enter a string and the program counts -the number of vowels in the text. For added complexity -have it report a sum of each vowel found. -""" - -from collections import defaultdict - -if __name__ == '__main__': - string = raw_input('Enter a string: ').lower() - - vowels = ['a', 'e', 'i', 'o', 'u'] - counts = defaultdict(int) - - for char in string: - if char in vowels: - counts[char] += 1 - - print counts.items() diff --git a/Text/count_words.py b/Text/count_words.py deleted file mode 100644 index 113c31f81..000000000 --- a/Text/count_words.py +++ /dev/null @@ -1,26 +0,0 @@ -""" -Count Words in a String - Counts the number of individual -words in a string and display the top 5/10 most used words. -""" - -from collections import defaultdict -import operator - -if __name__ == '__main__': - text = raw_input('Enter some text: \n') - words = text.split() # very naive approach, split at space - - counts = defaultdict(int) # no need to check existence of a key - - # find count of each word - for word in words: - counts[word] += 1 - - # sort the dict by the count of each word, returns a tuple (word, count) - sorted_counts = sorted(counts.iteritems(), \ - key=operator.itemgetter(1), \ - reverse=True) - - # print top 5 words - for (word,count) in sorted_counts[:5]: # thanks @jrwren for this! - print (word, count) diff --git a/Text/palindrome.py b/Text/palindrome.py deleted file mode 100644 index 43c7f4145..000000000 --- a/Text/palindrome.py +++ /dev/null @@ -1,12 +0,0 @@ -""" -Check if Palindrome - Checks if the string entered -by the user is a palindrome. That is that it reads -the same forwards as backwards like "racecar" -""" - -string = raw_input('Enter a string: ').lower() - -if string == string[::-1]: - print '%s is a palindrome' % string -else: - print '%s is not a palindrome' % string diff --git a/Text/piglatin.py b/Text/piglatin.py deleted file mode 100644 index 07af62233..000000000 --- a/Text/piglatin.py +++ /dev/null @@ -1,22 +0,0 @@ -""" -Pig Latin - Pig Latin is a game of alterations played -on the English language game. To create the Pig Latin -form of an English word the initial consonant sound is -transposed to the end of the word and an ay is affixed -(Ex.: "banana" would yield anana-bay). Read Wikipedia -for more information on rules. -""" - -word = raw_input('What\'s your word? ').lower() -vowels = 'aeiou' - -pig = 'ay' - -first = word[0] - -if first in vowels: - new = word + pig -else: - new = word[1:] + first + pig - -print new diff --git a/Text/reverse.py b/Text/reverse.py deleted file mode 100644 index 5cec022c3..000000000 --- a/Text/reverse.py +++ /dev/null @@ -1,8 +0,0 @@ -# -*- coding: cp1252 -*- -""" -Reverse a String - Enter a string and the program -will reverse it and print it out. -""" - -string = raw_input("Whatchu wanna say to me? ") -print "You say %s, I say %s" % (string, string[::-1]) diff --git a/Web/page_scraper.py b/Web/page_scraper.py deleted file mode 100644 index ccfd191fa..000000000 --- a/Web/page_scraper.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: cp1252 -*- -""" -Page Scraper - Create an application which connects to a -site and pulls out all links, or images, and saves them to -a list. Optional: Organize the indexed content and don�t -allow duplicates. Have it put the results into an easily -searchable index file. -""" - -import urllib2 -from bs4 import BeautifulSoup - - -def print_list(stuff): - print '\n'.join(stuff) - print '\n====================\n' - -if __name__ == '__main__': - - url = raw_input('Enter a URL: ') - - choice = input('What to scrape?\n1. Links\n2. Images\n3. Both\n') - - soup = BeautifulSoup(urllib2.urlopen(url).read()) - - if choice == 1 or choice == 3: - urls = [link.get('href') for link in soup.findAll('a')] - print 'URLs:' - print_list(urls) - if choice == 2 or choice ==3: - images = [image['src'] for image in soup.findAll("img")] - print 'Images:' - print_list(images) From f9e210b430ed729333f94993a7e552c1f9a1e82d Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Sat, 21 Sep 2013 14:28:54 +0000 Subject: [PATCH 03/19] Start working with this repo. First app Reverse String --- Text/ReverseString.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Text/ReverseString.java diff --git a/Text/ReverseString.java b/Text/ReverseString.java new file mode 100644 index 000000000..a7574f46b --- /dev/null +++ b/Text/ReverseString.java @@ -0,0 +1,19 @@ +import java.io.*; + +/** + * Reverse a String - Enter a string and the program + * will reverse it and print it out. + * @author RomanGotsiy (gotsijroman@gmail.com + */ + +public class ReverseString { + + public static void main(String args[]) + throws IOException { + System.out.println("Whatchu wanna say to me? "); + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String line = in.readLine(); + String reversed = new StringBuilder(line).reverse().toString(); + System.out.printf("You say '%s', I say '%s' \n",line,reversed); + } +} From 33af924dc547a2aa431a55e4ef1b6e9173b559aa Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Sat, 21 Sep 2013 21:17:39 +0000 Subject: [PATCH 04/19] Add Check a Palindrome programm --- .directory | 6 ++++++ .gitignore | 41 ++------------------------------------- Text/PalindromeCheck.java | 24 +++++++++++++++++++++++ 3 files changed, 32 insertions(+), 39 deletions(-) create mode 100644 .directory create mode 100644 Text/PalindromeCheck.java diff --git a/.directory b/.directory new file mode 100644 index 000000000..96e7351c4 --- /dev/null +++ b/.directory @@ -0,0 +1,6 @@ +[Dolphin] +Timestamp=2013,9,21,14,22,50 +Version=3 + +[Settings] +HiddenFilesShown=true diff --git a/.gitignore b/.gitignore index c084059d9..770ba2f58 100644 --- a/.gitignore +++ b/.gitignore @@ -1,39 +1,2 @@ -*.py[cod] - -# C extensions -*.so - -# Packages -*.egg -*.egg-info -dist -build -eggs -parts -bin -var -sdist -develop-eggs -.installed.cfg -lib -lib64 - -# Installer logs -pip-log.txt - -# Unit test / coverage reports -.coverage -.tox -nosetests.xml - -# Translations -*.mo - -# Mr Developer -.mr.developer.cfg -.project -.pydevproject - -# Komodo -.komodotools/ -*.komodoproject \ No newline at end of file +#.class files +*.class \ No newline at end of file diff --git a/Text/PalindromeCheck.java b/Text/PalindromeCheck.java new file mode 100644 index 000000000..4418f86ad --- /dev/null +++ b/Text/PalindromeCheck.java @@ -0,0 +1,24 @@ +import java.io.*; + +/** + * Check if Palindrome - Enter a string and the program + * will check it for polindrome and print result. + * @author RomanGotsiy (gotsijroman@gmail.com + */ + +public class PalindromeCheck { + + public static void main(String args[]) + throws IOException { + System.out.println("Enter string: "); + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String line = in.readLine().toLowerCase(); + + boolean res = line.equals(new StringBuilder(line).reverse().toString()); + + if (res) + System.out.println("Palindrome!"); + else + System.out.println("Oops. Not a palindrome. Try again!"); + } +} From f0bf3bdd3bb796a23da04aec0fb6022377c70ecf Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Sat, 21 Sep 2013 22:29:30 +0000 Subject: [PATCH 05/19] added ProductInventory programm --- Classes/ProductInventory.java | 78 +++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Classes/ProductInventory.java diff --git a/Classes/ProductInventory.java b/Classes/ProductInventory.java new file mode 100644 index 000000000..a53e03a70 --- /dev/null +++ b/Classes/ProductInventory.java @@ -0,0 +1,78 @@ +/* + * Product Inventory Project - Create an application which manages + * an inventory of products. Create a product class which has a + * price, id, and quantity on hand. Then create an inventory class + * which keeps track of various products and can sum up the inventory + * value. + * + * @author RomanGotsiy (gotsijroman@gmail.com) + */ + +import java.util.*; + +class Product { + public double price; + private int id; + private int quantity; + + public Product(int id, double price, int quantity){ + this.price = price; + this.id = id; + this.quantity = quantity; + } + + public void incQuantity(int qnt) { + this.quantity +=qnt; + } + + public void decQuantity(int qnt) { + this.quantity = Math.max(this.quantity-qnt, 0); + } + + public int getQuantity(){ + return this.quantity; + } + + public String toString(){ + return String.format("%d\t%.2f\t%d",id,price,quantity); + } +} + +class Inventory { + private List products; + + public Inventory(){ + products = new ArrayList(); + } + + public void addProduct(Product p){ + products.add(p); + } + + public void printInventory(){ + double sum = 0; + for(Product p : products){ + System.out.println(p.toString()); + sum+=p.price*p.getQuantity(); + } + System.out.println("Average is: " + sum); + } +} + +public class ProductInventory{ + public static void main(String args[]) { + Product p1 = new Product(1, 12.60, 4); + Product p2 = new Product(2, 23, 2); + Product p3 = new Product(3, 9.99, 2); + + Inventory inv = new Inventory(); + inv.addProduct(p1); + inv.addProduct(p2); + inv.addProduct(p3); + + p1.decQuantity(1); + p2.incQuantity(2); + + inv.printInventory(); + } +} From 340203f8ff6cf101ef1d0c744f22e9f12fc32539 Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Sun, 22 Sep 2013 12:49:52 +0000 Subject: [PATCH 06/19] Added Sort CSV programm --- Files/SortCSV.java | 148 +++++++++++++++++++++++++++++++++++++++++++++ Files/testfile.csv | 7 +++ 2 files changed, 155 insertions(+) create mode 100644 Files/SortCSV.java create mode 100644 Files/testfile.csv diff --git a/Files/SortCSV.java b/Files/SortCSV.java new file mode 100644 index 000000000..28a1831d6 --- /dev/null +++ b/Files/SortCSV.java @@ -0,0 +1,148 @@ +/**Sort Excel/CSV File Utility - Reads a file of records, + * sorts them, and then writes them back to the file. Allow + * the user to choose various sort style and sorting based + * on a particular field. + * + * @author Roman Gotsiy (gotsijroman@gmail.com) + * */ + +import java.io.*; +import java.util.*; + +class CSVFile { + + private List records; + + //constants for sortDirection + final public int SortASC = 1; + final public int SortDESC = -1; + private int sortDirection = SortASC; //1 for ASC, -1 for DESC + String fileName; + + private int colsCount=0; + + public CSVFile(String file) throws IOException{ + records = new ArrayList(); + fileName = file; + BufferedReader in = new BufferedReader(new FileReader(file)); + try { + String ln; + while( (ln = in.readLine()) !=null) { + colsCount = ln.split("\t").length; //FIXME + records.add(ln.split("\t")); + } + } + finally { + in.close(); + } + } + + public void print(){ + for(String[] arr : records){ + for (String s:arr) { + System.out.print(s+"\t"); + } + System.out.println(); + } + } + + public void save() throws IOException{ + BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); + + try { + for(String[] arr : records){ + for (String s:arr) { + out.write(s+"\t"); + } + out.write("\n"); + } + } + finally { + out.close(); + } + } + + public void setSortDirection(int direction){ + sortDirection = direction; + } + + public void sortByCol(final int i){ + + //comparator by specific col + Comparator comp = new Comparator(){ + public int compare(String[] a, String[] b){ + //reverse result if DESC (sortDirection = -1) + return sortDirection * a[i].compareTo(b[i]); + } + }; + + Collections.sort(records, comp); + } + + public int getColsCount(){ + return colsCount; + } +} + + + +class SortCSV { + private static BufferedReader in; + + private static String fileName; + + public static void main(String args[]) throws IOException{ + + in = new BufferedReader(new InputStreamReader(System.in)); + if (args.length<1){ + //promt user for input file + System.out.println("Enter path to .CSV file: "); + fileName = in.readLine(); + } else + { + fileName = args[0]; + } + + try { + CSVFile csv = new CSVFile(fileName); + + + csv.print(); + + int maxcol = csv.getColsCount(); + System.out.println( + String.format("Select sorting column (1-%d): [1] ",maxcol)); + + int sortCol = 1; + String res =in.readLine(); + + //if non-default + if (res.trim().length() != 0){ + sortCol = Integer.parseInt(res); + if ((sortCol<1) || (sortCol >maxcol)){ + System.out.println("Incorect column number"); + System.exit(0); + } + } + + String sortDirection = "1"; + System.out.println("Select sort direction"); + System.out.println("1. ASC"); + System.out.println("2. DESC"); + System.out.print("[1]:"); + sortDirection = in.readLine(); + if (sortDirection == "2") + csv.setSortDirection(csv.SortDESC); + + csv.sortByCol(sortCol-1); //-1 map from 1:n to 0:n-1 + csv.save(); + System.out.println("Sorted and saved to file"); + System.out.println("Would you like to see result before exit? (yes/no)[no]"); + if (in.readLine().trim().equals("yes")) + csv.print(); + } catch(IOException e) { + System.out.println("File doesn't exist"); + System.exit(0); + } + } +} \ No newline at end of file diff --git a/Files/testfile.csv b/Files/testfile.csv new file mode 100644 index 000000000..be6a00a2d --- /dev/null +++ b/Files/testfile.csv @@ -0,0 +1,7 @@ +1 Sun 2340 2001 +2 Microsoft 3523 2009 +3 Oracle 5453 1998 +4 IBM 5454 1978 +5 Google 3435 1999 +6 Intel 4344 1995 +7 AMD 3445 2002 From b114c3dfe5c9708aa5534918241b23d6695b6509 Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Mon, 23 Sep 2013 19:06:49 +0300 Subject: [PATCH 07/19] Added pi numbers calculation programm --- Numbers/PiCalculator.java | 105 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 Numbers/PiCalculator.java diff --git a/Numbers/PiCalculator.java b/Numbers/PiCalculator.java new file mode 100644 index 000000000..4f4c98640 --- /dev/null +++ b/Numbers/PiCalculator.java @@ -0,0 +1,105 @@ +/* + * Find PI to the Nth Digit - Enter a number and have the program + * generate PI up to that many decimal places. Keep a limit to how far + * the program will go. + * + * @author RomanGotsiy (gotsijroman@gmail.com) + */ + +import java.util.*; +import java.math.*; +import java.io.*; + +/** calculate pi using Spigout algorithm*/ +class PiSpigout { + private int reminders[]; //special array required for calculation + private int piDigits[]; //result array + private int remSize; //size of reminders array + private int digits; + private int tempInvalid = 0; //counter for temporary invalid digits + + + /**Realization of spigout algorighm: for explanation see + * http://cut-the-knot.org/Curriculum/Algorithms/SpigotForPi.shtml + */ + private void calc(){ + int carryOver = 0; + + //main iteration + for(int i=0; i0; k--) + { + sum = reminders[k]*10 + carryOver; + carryOver = (sum /(2*k +1)) * k; + reminders[k] = sum % (2*k+1); + } + //last step: k=0 + sum = reminders[0]*10 + carryOver; + int nextNumber = sum / 10; //calculated i-th number of pi + reminders[0] = sum % 10; + nextNumber = invalidDigitsControl(nextNumber, i); + piDigits[i] = nextNumber; //write new digit to result + } + } + + /** + * auxiliary function for algorithm + */ + private int invalidDigitsControl(int nextNumber, int position) { + if (nextNumber == 9) { + tempInvalid++; + return 9; + } + + if(nextNumber == 10) + { + for(int h = position-tempInvalid; h Date: Mon, 23 Sep 2013 19:21:36 +0300 Subject: [PATCH 08/19] More idiomatic code, using new Java 7 try-with-resources statement --- Files/SortCSV.java | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/Files/SortCSV.java b/Files/SortCSV.java index 28a1831d6..46e30f818 100644 --- a/Files/SortCSV.java +++ b/Files/SortCSV.java @@ -24,17 +24,14 @@ class CSVFile { public CSVFile(String file) throws IOException{ records = new ArrayList(); fileName = file; - BufferedReader in = new BufferedReader(new FileReader(file)); - try { + try(BufferedReader in = new BufferedReader(new FileReader(file))) + { String ln; while( (ln = in.readLine()) !=null) { colsCount = ln.split("\t").length; //FIXME records.add(ln.split("\t")); } } - finally { - in.close(); - } } public void print(){ @@ -47,9 +44,8 @@ public void print(){ } public void save() throws IOException{ - BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); - - try { + try(BufferedWriter out = new BufferedWriter(new FileWriter(fileName))) + { for(String[] arr : records){ for (String s:arr) { out.write(s+"\t"); @@ -57,9 +53,6 @@ public void save() throws IOException{ out.write("\n"); } } - finally { - out.close(); - } } public void setSortDirection(int direction){ From 07a424f4d84fabd7e91c8277ee14249610d91fa3 Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Mon, 23 Sep 2013 19:51:59 +0300 Subject: [PATCH 09/19] Added fibonacci generator programm --- Numbers/FibonacciGen.java | 46 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Numbers/FibonacciGen.java diff --git a/Numbers/FibonacciGen.java b/Numbers/FibonacciGen.java new file mode 100644 index 000000000..b9e4a7757 --- /dev/null +++ b/Numbers/FibonacciGen.java @@ -0,0 +1,46 @@ +/* Fibonacci Sequence - Enter a number and have the program generate the + * Fibonacci sequence to that number or to the Nth number. + * @author RomanGotsiy (gotsijroman@gmail.com) + */ + +import java.util.*; +import java.io.*; + +public class FibonacciGen { + + public static void main(String args[]) throws IOException{ + System.out.println("How many Fibonacci numbers should I print for you?:"); + int userAns = 10; + + try(BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) { + userAns = Integer.parseInt(in.readLine()); + } + + if (userAns<1) { System.exit(0); } + System.out.print("0"); + + if (userAns==1){ + System.out.println(); + System.exit(0); + } + + System.out.print(" 1"); + if (userAns==2) { + System.out.println(); + System.exit(0); + } + + //else + + int n_2 = 0; //(n-2)th number + int n_1 = 1; //(n-1)th number + for(int i=3; i Date: Wed, 25 Sep 2013 14:09:06 +0300 Subject: [PATCH 10/19] Added Factorial calculation programm --- Numbers/Factorial.java | 50 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Numbers/Factorial.java diff --git a/Numbers/Factorial.java b/Numbers/Factorial.java new file mode 100644 index 000000000..896ba2492 --- /dev/null +++ b/Numbers/Factorial.java @@ -0,0 +1,50 @@ +/** + * **Factorial Finder** - The Factorial of a positive integer, n, + * is defined as the product of the sequence n, n-1, n-2, ...1 and the + * factorial of zero, 0, is defined as being 1. + * Solve this using both loops and recursion. + */ + +import java.io.*; +import java.math.*; + +public class Factorial { + + private static BigInteger calcRecursive(int n){ + if (n==0) + return BigInteger.valueOf(1); + else if (n==1) + return BigInteger.valueOf(1); + else + return calcRecursive(n-1).multiply(BigInteger.valueOf(n)); + } + + private static BigInteger calcLoop(int n) { + BigInteger result = BigInteger.valueOf(1); + for(int i=n; i>1; i--) + { + result = result.multiply(BigInteger.valueOf(i)); + } + return result; + } + + public static void main(String args[]) throws IOException{ + System.out.println("Factorial calculator. Enter n: "); + int userAns=10; + BigInteger result; + try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){ + userAns = Integer.parseInt(br.readLine()); + + + System.out.print("Recurcive? (y/N): "); + if (br.readLine().toLowerCase().equals("y")) { + result = calcRecursive(userAns); + } else { + result = calcLoop(userAns); + } + } + + System.out.printf("Result: %d! = ",userAns); + System.out.println(result.toString()); + } +} From 3b1115a3ffc87f6e202753d4c473b6499a8fe254 Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Wed, 25 Sep 2013 23:45:45 +0300 Subject: [PATCH 11/19] Updated main README.md. Added new projects categories and ideas --- Classic Algorithms/README.md | 10 ++++++++++ Data Structures/README.md | 4 ++++ README.md | 37 +++++++++++++++++++++++++++++------- 3 files changed, 44 insertions(+), 7 deletions(-) create mode 100644 Classic Algorithms/README.md create mode 100644 Data Structures/README.md diff --git a/Classic Algorithms/README.md b/Classic Algorithms/README.md new file mode 100644 index 000000000..e3ee178c3 --- /dev/null +++ b/Classic Algorithms/README.md @@ -0,0 +1,10 @@ +Classic Algorithms +----------------- + +**Collatz Conjecture** - Start with a number *n > 1*. Find the number of steps it takes to reach one using the following process: If *n* is even, divide it by 2. If *n* is odd, multiply it by 3 and add 1. + +**Sorting** - Implement two types of sorting algorithms: Merge sort and bubble sort. + +**Closest pair problem** - The closest pair of points problem or closest pair problem is a problem of computational geometry: given *n* points in metric space, find a pair of points with the smallest distance between them. + +**Sieve of Eratosthenes** - The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes (below 10 million or so). diff --git a/Data Structures/README.md b/Data Structures/README.md new file mode 100644 index 000000000..1b5e05280 --- /dev/null +++ b/Data Structures/README.md @@ -0,0 +1,4 @@ +Data Structures +--------- + +**Inverted index** - An [Inverted Index](http://en.wikipedia.org/wiki/Inverted_index) is a data structure used to create full text search. Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be in memory. diff --git a/README.md b/README.md index 1c109d658..9aa50a140 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,20 @@ Mega Project List ======== +Some details about this repo: + +I will use Java to solve these. Why? Because I want to learn the language quickly. +The projects will not be made in the order posted. +I may not be able to complete all of them. +My method of solving them may not be the best. If you do not like my algorithm(s), please add a comment for the file/commit or open an issue, and I'll try to improve. +I will link to each project that I complete. Some will be in this same repo, some bigger ones will have dedicated repos. + Numbers --------- -**Find PI to the Nth Digit** - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. +[**Find PI to the Nth Digit**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/PiCalculator.java) - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. -**Fibonacci Sequence** - Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number. +[**Fibonacci Sequence**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/FibonacciGen.java) - Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number. **Prime Factorization** - Have the user enter a number and find all Prime Factors (if there are any) and display them. @@ -32,7 +40,7 @@ Numbers **Tax Calculator** - Asks the user to enter a cost and either a country or state tax. It then returns the tax plus the total cost with tax. -**Factorial Finder** - The Factorial of a positive integer, n, is defined as the product of the sequence n, n-1, n-2, ...1 and the factorial of zero, 0, is defined as being 1. Solve this using both loops and recursion. +[**Factorial Finder**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/Factorial.java) - The Factorial of a positive integer, n, is defined as the product of the sequence n, n-1, n-2, ...1 and the factorial of zero, 0, is defined as being 1. Solve this using both loops and recursion. **Complex Number Algebra** - Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. @@ -50,18 +58,33 @@ Graph **Dijkstra’s Algorithm** - Create a program that finds the shortest path through a graph using its edges. +Data Structures +--------- + +**Inverted index** - An [Inverted Index](http://en.wikipedia.org/wiki/Inverted_index) is a data structure used to create full text search. Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be in memory. + +Classic Algorithms +----------------- + +**Collatz Conjecture** - Start with a number *n > 1*. Find the number of steps it takes to reach one using the following process: If *n* is even, divide it by 2. If *n* is odd, multiply it by 3 and add 1. + +**Sorting** - Implement two types of sorting algorithms: Merge sort and bubble sort. + +**Closest pair problem** - The closest pair of points problem or closest pair problem is a problem of computational geometry: given *n* points in metric space, find a pair of points with the smallest distance between them. + +**Sieve of Eratosthenes** - The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes (below 10 million or so). Text --------- -**Reverse a String** - Enter a string and the program will reverse it and print it out. +[**Reverse a String**](https://github.com/RomanGotsiy/LearningJava/blob/master/Text/ReverseString.java) - Enter a string and the program will reverse it and print it out. **Pig Latin** - Pig Latin is a game of alterations played on the English language game. To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word and an ay is affixed (Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules. **Count Vowels** - Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found. -**Check if Palindrome** - Checks if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like “racecar” +[**Check if Palindrome**](https://github.com/RomanGotsiy/LearningJava/blob/master/Text/PalindromeCheck.java) - Checks if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like “racecar” **Count Words in a String** - Counts the number of individual words in a string. For added complexity read these strings in from a text file and generate a summary. @@ -105,7 +128,7 @@ Networking Classes --------- -**Product Inventory Project** - Create an application which manages an inventory of products. Create a product class which has a price, id, and quantity on hand. Then create an *inventory* class which keeps track of various products and can sum up the inventory value. +[**Product Inventory Project**](https://github.com/RomanGotsiy/LearningJava/blob/master/Classes/ProductInventory.java) - Create an application which manages an inventory of products. Create a product class which has a price, id, and quantity on hand. Then create an *inventory* class which keeps track of various products and can sum up the inventory value. **Airline / Hotel Reservation System** - Create a reservation system which books airline seats or hotel rooms. It charges various rates for particular sections of the plane or hotel. Example, first class is going to cost more than coach. Hotel rooms have penthouse suites which cost more. Keep track of when rooms will be available and can be scheduled. @@ -160,7 +183,7 @@ Files **File Explorer** - Create your own simple windows explorer program. Add feature(s) you always thought are missing from MS Windows Explorer or Mac Finder. -**Sort Excel/CSV File Utility** - Reads a file of records, sorts them, and then writes them back to the file. Allow the user to choose various sort style and sorting based on a particular field. +[**Sort Excel/CSV File Utility**](https://github.com/RomanGotsiy/LearningJava/blob/master/Files/SortCSV.java) - Reads a file of records, sorts them, and then writes them back to the file. Allow the user to choose various sort style and sorting based on a particular field. **Create Zip File Maker** - The user enters various files from different directories and the program zips them up into a zip file. *Optional: Apply actual compression to the files. Start with Huffman Algorithm.* From 3d9e1b276744168ab755a51928e18079040586af Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Wed, 25 Sep 2013 23:45:45 +0300 Subject: [PATCH 12/19] Updated main README.md. Added new projects categories and ideas --- Classic Algorithms/README.md | 10 ++++++++++ Data Structures/README.md | 4 ++++ README.md | 37 +++++++++++++++++++++++++++++------- 3 files changed, 44 insertions(+), 7 deletions(-) create mode 100644 Classic Algorithms/README.md create mode 100644 Data Structures/README.md diff --git a/Classic Algorithms/README.md b/Classic Algorithms/README.md new file mode 100644 index 000000000..e3ee178c3 --- /dev/null +++ b/Classic Algorithms/README.md @@ -0,0 +1,10 @@ +Classic Algorithms +----------------- + +**Collatz Conjecture** - Start with a number *n > 1*. Find the number of steps it takes to reach one using the following process: If *n* is even, divide it by 2. If *n* is odd, multiply it by 3 and add 1. + +**Sorting** - Implement two types of sorting algorithms: Merge sort and bubble sort. + +**Closest pair problem** - The closest pair of points problem or closest pair problem is a problem of computational geometry: given *n* points in metric space, find a pair of points with the smallest distance between them. + +**Sieve of Eratosthenes** - The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes (below 10 million or so). diff --git a/Data Structures/README.md b/Data Structures/README.md new file mode 100644 index 000000000..1b5e05280 --- /dev/null +++ b/Data Structures/README.md @@ -0,0 +1,4 @@ +Data Structures +--------- + +**Inverted index** - An [Inverted Index](http://en.wikipedia.org/wiki/Inverted_index) is a data structure used to create full text search. Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be in memory. diff --git a/README.md b/README.md index 1c109d658..8d92ad984 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,20 @@ Mega Project List ======== +Some details about this repo: + +* I will use Java to solve these. Why? Because I want to learn the language quickly. +* The projects will not be made in the order posted. +* I may not be able to complete all of them. +* My method of solving them may not be the best. If you do not like my algorithm(s), please add a comment for the file/commit or open an issue, and I'll try to improve. +* I will link to each project that I complete. Some will be in this same repo, some bigger ones will have dedicated repos. + Numbers --------- -**Find PI to the Nth Digit** - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. +[**Find PI to the Nth Digit**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/PiCalculator.java) - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. -**Fibonacci Sequence** - Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number. +[**Fibonacci Sequence**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/FibonacciGen.java) - Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number. **Prime Factorization** - Have the user enter a number and find all Prime Factors (if there are any) and display them. @@ -32,7 +40,7 @@ Numbers **Tax Calculator** - Asks the user to enter a cost and either a country or state tax. It then returns the tax plus the total cost with tax. -**Factorial Finder** - The Factorial of a positive integer, n, is defined as the product of the sequence n, n-1, n-2, ...1 and the factorial of zero, 0, is defined as being 1. Solve this using both loops and recursion. +[**Factorial Finder**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/Factorial.java) - The Factorial of a positive integer, n, is defined as the product of the sequence n, n-1, n-2, ...1 and the factorial of zero, 0, is defined as being 1. Solve this using both loops and recursion. **Complex Number Algebra** - Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. @@ -50,18 +58,33 @@ Graph **Dijkstra’s Algorithm** - Create a program that finds the shortest path through a graph using its edges. +Data Structures +--------- + +**Inverted index** - An [Inverted Index](http://en.wikipedia.org/wiki/Inverted_index) is a data structure used to create full text search. Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be in memory. + +Classic Algorithms +----------------- + +**Collatz Conjecture** - Start with a number *n > 1*. Find the number of steps it takes to reach one using the following process: If *n* is even, divide it by 2. If *n* is odd, multiply it by 3 and add 1. + +**Sorting** - Implement two types of sorting algorithms: Merge sort and bubble sort. + +**Closest pair problem** - The closest pair of points problem or closest pair problem is a problem of computational geometry: given *n* points in metric space, find a pair of points with the smallest distance between them. + +**Sieve of Eratosthenes** - The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes (below 10 million or so). Text --------- -**Reverse a String** - Enter a string and the program will reverse it and print it out. +[**Reverse a String**](https://github.com/RomanGotsiy/LearningJava/blob/master/Text/ReverseString.java) - Enter a string and the program will reverse it and print it out. **Pig Latin** - Pig Latin is a game of alterations played on the English language game. To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word and an ay is affixed (Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules. **Count Vowels** - Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found. -**Check if Palindrome** - Checks if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like “racecar” +[**Check if Palindrome**](https://github.com/RomanGotsiy/LearningJava/blob/master/Text/PalindromeCheck.java) - Checks if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like “racecar” **Count Words in a String** - Counts the number of individual words in a string. For added complexity read these strings in from a text file and generate a summary. @@ -105,7 +128,7 @@ Networking Classes --------- -**Product Inventory Project** - Create an application which manages an inventory of products. Create a product class which has a price, id, and quantity on hand. Then create an *inventory* class which keeps track of various products and can sum up the inventory value. +[**Product Inventory Project**](https://github.com/RomanGotsiy/LearningJava/blob/master/Classes/ProductInventory.java) - Create an application which manages an inventory of products. Create a product class which has a price, id, and quantity on hand. Then create an *inventory* class which keeps track of various products and can sum up the inventory value. **Airline / Hotel Reservation System** - Create a reservation system which books airline seats or hotel rooms. It charges various rates for particular sections of the plane or hotel. Example, first class is going to cost more than coach. Hotel rooms have penthouse suites which cost more. Keep track of when rooms will be available and can be scheduled. @@ -160,7 +183,7 @@ Files **File Explorer** - Create your own simple windows explorer program. Add feature(s) you always thought are missing from MS Windows Explorer or Mac Finder. -**Sort Excel/CSV File Utility** - Reads a file of records, sorts them, and then writes them back to the file. Allow the user to choose various sort style and sorting based on a particular field. +[**Sort Excel/CSV File Utility**](https://github.com/RomanGotsiy/LearningJava/blob/master/Files/SortCSV.java) - Reads a file of records, sorts them, and then writes them back to the file. Allow the user to choose various sort style and sorting based on a particular field. **Create Zip File Maker** - The user enters various files from different directories and the program zips them up into a zip file. *Optional: Apply actual compression to the files. Start with Huffman Algorithm.* From ca9a7792588b043ad221ba017069198599f7ad32 Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Thu, 26 Sep 2013 01:09:02 +0300 Subject: [PATCH 13/19] Added Prime factorization programm --- Numbers/Factorization.java | 39 ++++++++++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 Numbers/Factorization.java diff --git a/Numbers/Factorization.java b/Numbers/Factorization.java new file mode 100644 index 000000000..41c6d2c45 --- /dev/null +++ b/Numbers/Factorization.java @@ -0,0 +1,39 @@ +/** **Prime Factorization** - Have the user enter + * a number and find all Prime Factors (if there are any) and display them. + */ + +import java.io.*; +import java.math.*; +import java.util.*; + +public class Factorization { + /**one of the simplest factorization algorithm.*/ + private static List trialDivision(int n){ + List result = new ArrayList(); + long square = Math.round((Math.sqrt(n))) + 1; + + int d=2; //divisor + while(n>1){ + if (d>square) break; + while(n%d == 0){ + result.add(d); + n/=d; + } + d+=1; + } + return result; + } + + public static void main(String args[]) throws IOException{ + System.out.print("Input a number: "); + int n=10; + try(Scanner in= new Scanner(new InputStreamReader(System.in))){ + n = in.nextInt(); + } + System.out.println(); + + System.out.printf("Factorization of number %d: ", n); + List res = trialDivision(n); + System.out.println(res.toString()); + } +} \ No newline at end of file diff --git a/README.md b/README.md index 8d92ad984..0dbcf863a 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Numbers [**Fibonacci Sequence**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/FibonacciGen.java) - Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number. -**Prime Factorization** - Have the user enter a number and find all Prime Factors (if there are any) and display them. +[**Prime Factorization**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/Factorization.java) - Have the user enter a number and find all Prime Factors (if there are any) and display them. **Next Prime Number** - Have the program find prime numbers until the user chooses to stop asking for the next one. From e3697779cf63daa3fedfcd71bb06a6a99ba7e3e7 Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Fri, 27 Sep 2013 00:35:29 +0300 Subject: [PATCH 14/19] Added Next Prime programm --- Numbers/NextPrime.java | 36 ++++++++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 Numbers/NextPrime.java diff --git a/Numbers/NextPrime.java b/Numbers/NextPrime.java new file mode 100644 index 000000000..49160eb5a --- /dev/null +++ b/Numbers/NextPrime.java @@ -0,0 +1,36 @@ +/** Next Prime Number - Have the program find prime numbers until the user chooses + * to stop asking for the next one. + * */ + +import java.util.*; +import java.io.*; + +public class NextPrime { + private static List primes; + + private static boolean check(int n) { + for(int i : primes) + if ((n%i == 0) && (n!=i)) return false; + return true; + } + + public static void main(String args[]) throws IOException{ + primes = new LinkedList(); + primes.add(2); + System.out.println("Prime numbers generator. For next press [ENTER], for exit - CTRL+D"); + + int p = 2; + System.out.print(2); + while(System.in.read()>=0) { //-1 if eof + while(true){ + p++; + if (check(p)){ + primes.add(p); + System.out.print(p); + break; + } + } + } + System.out.println(); + } +} \ No newline at end of file diff --git a/README.md b/README.md index 0dbcf863a..850c2a2a9 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Numbers [**Prime Factorization**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/Factorization.java) - Have the user enter a number and find all Prime Factors (if there are any) and display them. -**Next Prime Number** - Have the program find prime numbers until the user chooses to stop asking for the next one. +[**Next Prime Number**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/NextPrime.java) - Have the program find prime numbers until the user chooses to stop asking for the next one. **Find Cost of Tile to Cover W x H Floor** - Calculate the total cost of tile it would take to cover a floor plan of width and height, using a cost entered by the user. From 1ea1db15ca4f3f4de99305bffcef51b83adf367e Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Mon, 30 Sep 2013 20:53:28 +0300 Subject: [PATCH 15/19] Find Cost of Tile to Cover W x H Floor done --- Numbers/TileCost.java | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Numbers/TileCost.java diff --git a/Numbers/TileCost.java b/Numbers/TileCost.java new file mode 100644 index 000000000..f687b14ba --- /dev/null +++ b/Numbers/TileCost.java @@ -0,0 +1,31 @@ +/** + * Find Cost of Tile to Cover W x H Floor - Calculate the total + * cost of tile it would take to cover a floor plan of width and height, + * using a cost entered by the user. + * + * @author Roman Gotsiy (gotsijroman@gmail.com) + */ + +import java.io.*; +import java.util.*; + +class TileCost { + public static void main(String args[]){ + try(Scanner s = new Scanner(new InputStreamReader(System.in))) { + System.out.println("Input cost per sq. meter: "); + float cost = s.nextFloat(); + System.out.println("Input floor width: "); + float width = s.nextFloat(); + System.out.println("Input floor height: "); + float height = s.nextFloat(); + + + System.out.printf("The total cost is $%.2f for %.2f square meters\n", + cost*width*height,width*height); + } + catch(InputMismatchException e){ + System.out.println("Incorrect number. Terminating"); + System.exit(0); + } + } +} \ No newline at end of file From ce80b6d4e49f3f2c5ff1e1e0132fe2c6962298a9 Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Mon, 30 Sep 2013 20:53:28 +0300 Subject: [PATCH 16/19] Find Cost of Tile to Cover W x H Floor done --- Numbers/TileCost.java | 31 +++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 Numbers/TileCost.java diff --git a/Numbers/TileCost.java b/Numbers/TileCost.java new file mode 100644 index 000000000..f687b14ba --- /dev/null +++ b/Numbers/TileCost.java @@ -0,0 +1,31 @@ +/** + * Find Cost of Tile to Cover W x H Floor - Calculate the total + * cost of tile it would take to cover a floor plan of width and height, + * using a cost entered by the user. + * + * @author Roman Gotsiy (gotsijroman@gmail.com) + */ + +import java.io.*; +import java.util.*; + +class TileCost { + public static void main(String args[]){ + try(Scanner s = new Scanner(new InputStreamReader(System.in))) { + System.out.println("Input cost per sq. meter: "); + float cost = s.nextFloat(); + System.out.println("Input floor width: "); + float width = s.nextFloat(); + System.out.println("Input floor height: "); + float height = s.nextFloat(); + + + System.out.printf("The total cost is $%.2f for %.2f square meters\n", + cost*width*height,width*height); + } + catch(InputMismatchException e){ + System.out.println("Incorrect number. Terminating"); + System.exit(0); + } + } +} \ No newline at end of file diff --git a/README.md b/README.md index 850c2a2a9..f74646a8d 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Numbers [**Next Prime Number**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/NextPrime.java) - Have the program find prime numbers until the user chooses to stop asking for the next one. -**Find Cost of Tile to Cover W x H Floor** - Calculate the total cost of tile it would take to cover a floor plan of width and height, using a cost entered by the user. +[**Find Cost of Tile to Cover W x H Floor**](https://github.com/RomanGotsiy/LearningJava/blob/master/Numbers/TileCost.java) - Calculate the total cost of tile it would take to cover a floor plan of width and height, using a cost entered by the user. **Mortgage Calculator** - Calculate the monthly payments of a fixed term mortgage over given Nth terms at a given interest rate. Also figure out how long it will take the user to pay back the loan. From 125a2efacc2b244159982798c51496d4a0ab7ae0 Mon Sep 17 00:00:00 2001 From: Roman Gotsiy Date: Sat, 11 Jan 2014 18:05:35 +0200 Subject: [PATCH 17/19] Inverted index done --- Data Structures/InvertedIndex.java | 78 ++++++++++++++++++++++++++++++ Data Structures/testfile1.txt | 1 + Data Structures/testfile2.txt | 4 ++ README.md | 2 +- 4 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 Data Structures/InvertedIndex.java create mode 100644 Data Structures/testfile1.txt create mode 100644 Data Structures/testfile2.txt diff --git a/Data Structures/InvertedIndex.java b/Data Structures/InvertedIndex.java new file mode 100644 index 000000000..3a6f1cf99 --- /dev/null +++ b/Data Structures/InvertedIndex.java @@ -0,0 +1,78 @@ +/* + * InvertedIndex - Given a set of text files, implement a program to create an + * inverted index. Also create a user interface to do a search using that inverted + * index which returns a list of files that contain the query term / terms. + * The search index can be in memory. + * + * @author RomanGotsiy (gotsijroman@gmail.com) + */ +import java.io.*; +import java.util.*; + +class Index { + Map sources; + HashMap> index; + + Index(){ + sources = new HashMap(); + index = new HashMap>(); + } + + public void buildIndex(String[] files){ + int i = 0; + for(String fileName:files){ + + + try(BufferedReader file = new BufferedReader(new FileReader(fileName))) + { + sources.put(i,fileName); + String ln; + while( (ln = file.readLine()) !=null) { + String[] words = ln.split("\\W+"); + for(String word:words){ + word = word.toLowerCase(); + if (!index.containsKey(word)) + index.put(word, new HashSet()); + index.get(word).add(i); + } + } + } catch (IOException e){ + System.out.println("File "+fileName+" not found. Skip it"); + } + i++; + } + + } + + public void find(String phrase){ + String[] words = phrase.split("\\W+"); + HashSet res = new HashSet(index.get(words[0].toLowerCase())); + for(String word: words){ + res.retainAll(index.get(word)); + } + + if(res.size()==0) { + System.out.println("Not found"); + return; + } + System.out.println("Found in: "); + for(int num : res){ + System.out.println("\t"+sources.get(num)); + } + } +} + +public class InvertedIndex { + + + public static void main(String args[]) throws IOException{ + Index index = new Index(); + index.buildIndex(new String[]{"testfile1.txt","testfile2.txt"}); + + System.out.println("Print search phrase: "); + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String phrase = in.readLine(); + + index.find(phrase); + } +} \ No newline at end of file diff --git a/Data Structures/testfile1.txt b/Data Structures/testfile1.txt new file mode 100644 index 000000000..29f696909 --- /dev/null +++ b/Data Structures/testfile1.txt @@ -0,0 +1 @@ +In computer science, an inverted index (also referred to as postings file or inverted file) is an index data structure storing a mapping from content, such as words or numbers, to its locations in a database file, or in a document or a set of documents. The purpose of an inverted index is to allow fast full text searches, at a cost of increased processing when a document is added to the database. The inverted file may be the database file itself, rather than its index. It is the most popular data structure used in document retrieval systems,[1] used on a large scale for example in search engines. Several significant general-purpose mainframe-based database management systems have used inverted list architectures, including ADABAS, DATACOM/DB, and Model 204. diff --git a/Data Structures/testfile2.txt b/Data Structures/testfile2.txt new file mode 100644 index 000000000..b2e70c3ca --- /dev/null +++ b/Data Structures/testfile2.txt @@ -0,0 +1,4 @@ +The inverted index data structure is a central component of a typical search engine indexing algorithm. A goal of a search engine implementation is to optimize the speed of the query: find the documents where word X occurs. Once a forward index is developed, which stores lists of words per document, it is next inverted to develop an inverted index. Querying the forward index would require sequential iteration through each document and to each word to verify a matching document. The time, memory, and processing resources to perform such a query are not always technically realistic. Instead of listing the words per document in the forward index, the inverted index data structure is developed which lists the documents per word. +With the inverted index created, the query can now be resolved by jumping to the word id (via random access) in the inverted index. +In pre-computer times, concordances to important books were manually assembled. These were effectively inverted indexes with a small amount of accompanying commentary that required a tremendous amount of effort to produce. +In bioinformatics, inverted indexes are very important in the sequence assembly of short fragments of sequenced DNA. One way to find the source of a fragment is to search for it against a reference DNA sequence. A small number of mismatches (due to differences between the sequenced DNA and reference DNA, or errors) can be accounted for by dividing the fragment into smaller fragments—at least one subfragment is likely to match the reference DNA sequence. The matching requires constructing an inverted index of all substrings of a certain length from the reference DNA sequence. Since the human DNA contains more than 3 billion base pairs, and we need to store a DNA substring for every index, and a 32-bit integer for index itself, the storage requirement for such an inverted index would probably be in the tens of gigabytes. diff --git a/README.md b/README.md index f74646a8d..876c10e5e 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Graph Data Structures --------- -**Inverted index** - An [Inverted Index](http://en.wikipedia.org/wiki/Inverted_index) is a data structure used to create full text search. Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be in memory. +[**Inverted index**](https://github.com/RomanGotsiy/LearningJava/blob/master/Data%20Structures/InvertedIndex.java.java) - An [Inverted Index](http://en.wikipedia.org/wiki/Inverted_index) is a data structure used to create full text search. Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be in memory. Classic Algorithms ----------------- From d6d55b23f6e6219f39d577a6e09e12302db6034a Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Sat, 11 Jan 2014 18:15:01 +0200 Subject: [PATCH 18/19] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 876c10e5e..dde180d0d 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Graph Data Structures --------- -[**Inverted index**](https://github.com/RomanGotsiy/LearningJava/blob/master/Data%20Structures/InvertedIndex.java.java) - An [Inverted Index](http://en.wikipedia.org/wiki/Inverted_index) is a data structure used to create full text search. Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be in memory. +[**Inverted index**](https://github.com/RomanGotsiy/LearningJava/blob/master/Data Structures/InvertedIndex.java.java) - An [Inverted Index](http://en.wikipedia.org/wiki/Inverted_index) is a data structure used to create full text search. Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be in memory. Classic Algorithms ----------------- From 017111c99f2687f84e384a453314f5da00d24229 Mon Sep 17 00:00:00 2001 From: RomanGotsiy Date: Sat, 11 Jan 2014 18:16:21 +0200 Subject: [PATCH 19/19] oops. update readme again --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dde180d0d..88c012ceb 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Graph Data Structures --------- -[**Inverted index**](https://github.com/RomanGotsiy/LearningJava/blob/master/Data Structures/InvertedIndex.java.java) - An [Inverted Index](http://en.wikipedia.org/wiki/Inverted_index) is a data structure used to create full text search. Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be in memory. +[**Inverted index**](https://github.com/RomanGotsiy/LearningJava/blob/master/Data%20Structures/InvertedIndex.java) - An [Inverted Index](http://en.wikipedia.org/wiki/Inverted_index) is a data structure used to create full text search. Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be in memory. Classic Algorithms -----------------