Author Archives: MantasCode

C#: Generate 10 unique integers (1-10) using only 10 steps

In this fun little program I force my computer to randomly generate a list of ten unique numbers, one through ten, using only 10 steps.

I run the program until it randomly meets all these conditions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SandCastlePractice
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Generate a distinct list of 10 random numbers,"
                +" ranging from 1 to 10, with the lowest amount of steps (10)");
            DateTime timeStart = DateTime.Now;
            Console.WriteLine("Time Started : "+ timeStart.TimeOfDay+"\r\n");
 
            //Counter for total times it will try
            int Total_Iterations = 0;
            //Decrementor for lowest amount of steps to create distinct list
            int lowestStep = 10000;
            //int used to see if lowest step changed
            int laststep = 0; 
            //display list when lowest steps are achieved
            LinkedList<int> displayList = new LinkedList<int>();
 
            //while the lowest steps arnt 10, keep trying
            while (lowestStep != 10)
            {
                Total_Iterations++;
                //steps counter
                int iSteps = 0;
                //bool to check if list of 10 is distinct
                bool isListDistinct = false;
                //temp LinkedList to be populated over and over
                LinkedList<int> numList = new LinkedList<int>();
                //create random number object
                Random random = new Random();
                while (!isListDistinct)
                {
                    ++iSteps;
                    //get a random number 0 - 10
                    int randomNumber = random.Next(0, 10);
                    //increment it by one so its 1-10, instead of 0-9
                    randomNumber++;
                    //if temp LinkedList doesn't contain generated int, add it
                    if (!numList.Contains(randomNumber))
                        numList.AddLast(randomNumber);
                    //when the list has 10 elements stop looping
                    if (numList.Count == 10)
                    {
                        isListDistinct = true;
                        //check if lowest amount of step is less then previous
                        if (iSteps < lowestStep)
                            lowestStep = iSteps;
                    }
                }
                //if lowest amount of steps got lower
                if (laststep != lowestStep)
                {
                    //Display new low
                    Console.WriteLine("lowest steps so far : " + lowestStep);
                    //when steps taken are 10, set current temp LinkedList 
                    //to Display List
                    if (lowestStep == 10)
                        displayList = numList;
 
                }
                laststep = lowestStep;
                isListDistinct = false;
            }
 
            Console.WriteLine("---------------------\r\n");
            //display the distinct list of ten, that only took 10 steps to generate
            foreach (var num in displayList)
            {
                Console.Write(num + " ");
            }
            Console.WriteLine();
            Console.WriteLine("How many times did it have to try?  " + 
                Total_Iterations.ToString("#,##0"));
            DateTime timeFinish = DateTime.Now;
            Console.WriteLine("How Long did it take?               "+  
                (timeFinish-timeStart)   );
        }
    }
}

C#: Sort lists of bits by which end they congregate at.

Say, you’ve got several lists which contain two potential values for each item, such as:

10010
11000
00101

and you’d like to sort them like a seesaw, from most weighed down on the right to most weighed down on the left.

 


and sort them like so 0010110010, 11000

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Polarity
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("indeed.");
            Random random = new Random();
            LinkedList[] arrayLL = new LinkedList[10];
 
            //Make 10 lists: each with 10 items
            //for each set of items there must be three 1's, in random locations
            //then sort the ten lists by their closeness towards the end 
 
            for (int i = 0; i &lt; 10; i++)
            {
                LinkedList distinctOrder = new LinkedList();
                while (distinctOrder.Count &lt; 10)
                {
                    int randomNumber = random.Next(0, 10);
                    if (!distinctOrder.Contains(randomNumber))
                        distinctOrder.AddLast(randomNumber);
                }
                Console.WriteLine();
 
                //now that i have my distinct list random 1-10 order
                //make 0,1,2 into 1's and the rest into 0's
                LinkedList polList = new LinkedList();
                foreach (var num in distinctOrder)
                {
                    if (num == 0 || num == 1 || num == 2)
                        polList.AddLast(1);
                    else
                        polList.AddLast(0);
                }
                foreach (var num in polList)
                {
                    Console.Write(num + " ");
                }
                arrayLL[i] = polList;
            }
 
            Console.WriteLine("\r\n-------------------");
            Dictionary dictionary = new Dictionary();
 
            //figure out the score of each line and add it to dictionary
            //the position of the 1's indicidate their score towards the end
            for (int i = 0; i &lt; arrayLL.Length; i++)
            {
                int[] thisLine = arrayLL[i].ToArray();
                int sum = 0;
                string line = "";
                for (int k = 0; k &lt; thisLine.Length; k++)                 
                {                    
                         line += " " + thisLine[k];                    
                         if (thisLine[k] == 1)                         
                                  sum += k;                 
                 }                 
                 Console.WriteLine(line+"    "+sum);                
                 //add string of 10 to dictionary object                
                 //Warning! this will crash if the randomized string repeats                
                dictionary.Add(line, sum);                                 
          }             
           Console.WriteLine("-------------------");             
            //sort lines from highest score to lowest             
            var sortedDict = (from entry in dictionary orderby entry.Value descending select entry).ToDictionary(pair =&gt; pair.Key, pair =&gt; pair.Value);
            foreach (var strKey in sortedDict.Keys)
                Console.WriteLine(strKey);
 
        }
    }
}

Android: Erowid

“Documenting the Complex Relationships Between Humans & Psychoactives” – erowid.org

A while ago I decided to index part of the erowid site into a free and easy to use android application. Here is the result of what I was willing to index from the site.

Download for free on GooglePlay.

https://play.google.com/store/apps/details?id=Erowid.MantasCode

All content from Erowid.org

Update: A lot of positive reviews from Google Play and people asking for the experience reports to be statically indexed into the Application. Hopefully, I will be given those to add soon. Thanks for the downloads!

Android : Radiology Quiz

Part 3 of series on gamification of a dataset.

Part 1 Part 2

A randomized multiple choice quiz which tests the players knowledge of different relationships from the RadLex Ontology.

Download and play for free on GooglePlay

https://play.google.com/store/apps/details?id=MantasCode.RadQuiz

Relationship sets used:

{“anatomical_site”, “blood_supply_of”, “branch_of”, “constitutional_part_of”, “contained_in”, “contains”, “drains_into”, “has_blood_supply”, “has_branch”, “has_constitutional_part”, “has_innervation_source”, “has_member”, “lymphatic_drainage_of”, “member_of”, “projects_from”, “projects_to”, “receives_drainage_from”, “receives_input_from”, “receives_projection_from”, “related_condition”, “related_modality”, “segment_of”, “sends_output_to”};

^ each one of these sets is the same as the Character to Location set from Part 1. However, these are much larger.

over 12,000 questions .

update:

Added count down timer, added correct answer display if incorrect answer chosen, reformatted button layouts, changed some colors, and added some annoying sounds  XD

 

Android: Gamification of a DataSET / Part 2

I have turned the previous post Java: LOL!: Gamification of a DataSET into an Android Application.  This example project will show you how to gamify a simple multiple choice quiz in order to engage the user more.

Free download this example app can be found on GooglePlay.

https://play.google.com/store/apps/details?id=Quizer.Quiz

Game Mechanics and Rewards/Risks:

The player gets asked a random question from the dataset and is presented with a multiple choice of 4 answers.   The correct answer will reward the him/her with a banana (+).  If the player chooses wrong he will lose a banana (-) or even go into banana debt.  The banana is an ongoing indicator of status.  If the player accumulates  more then 20 bananas he will unlock this:  (its a sushi roll).  Also, there’s gooseberries.  For every 10 correct answers the player will get 1 gooseberry .

Continue reading

Java: LOL!: Gamification of a DataSET :D

Randomized multiple choice quiz of the relationship sets of Fallout 2 Characters and their Locations.

(Character (is from/is related to) Location)
(Concept 1 -> Relationship -> Concept 2)
Example:
( Sulik from Klamath)

Now we want to ask a random question, so we get a random number between 1 and 13 , and pick that row in the data set.

We roll the dice and get “1” so we take the first data row and ask

“Where is Sulik Found?”

This quiz is going to be multiple choice of 4, so we need 3 random incorrect answers, and we need to randomize the correct answer’s location somewhere within the set of incorrect answers.

Make a List of 3 unique/distinct incorrect answers out of the remaining values within the hashtable.  Again, exclude the correct answer  and handle any duplicates.  So in Sulik‘s case, the distinct set of potential incorrect answers looks like this.

Pick another random number and pick 3 distinct values from this list.  Then, append the 3 incorrect values with the correct one.  Pick another random random number 1-4 and display the randomized answers 4 times for “a.)” through “d.)“.

code for now…

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Random;
 
public class QuizStructure
{
	public static void main(String[] args)
	{
		LinkedList EveryPotentialQuestion_AnswerSet = new LinkedList();
 
		//HOW TO MAKE A Randomized QUIZ off OF a DataSet
 
		//Gamification of a DataSET// LOL :D
 
		System.out.println("indeed.");
		Hashtable Character_to_Location = new Hashtable();
 
		//"FALLOUT 2 Black Isle Character to Location" Relationship//
		//( Character - Is_From - Location )//
		//( Concept - Relationship - Concept )
		Character_to_Location.put("Sulik", "Klamath");
		Character_to_Location.put("Vic", "Den");
		Character_to_Location.put("Miria", "Modoc");
		Character_to_Location.put("Davin", "Modoc");
		Character_to_Location.put("Cassidy", "Vault City");
		Character_to_Location.put("Lenny", "Gecko");
		Character_to_Location.put("Marcus", "Broken Hills");
		Character_to_Location.put("Myron", "New Reno Stables");
		Character_to_Location.put("Skynet Robot", "Sierra Army Depot");
	        Character_to_Location.put("K-9", "Navarro");
		Character_to_Location.put("Goris", "Vault 13");
		Character_to_Location.put("Cyber Dog", "NCR");
		Character_to_Location.put("Dogmeat", "Cafe of Broken Dreams");
		System.out.println(Character_to_Location.toString());
		Enumeration keys = Character_to_Location.keys();
		while( keys.hasMoreElements() )
		{
			Object key = keys.nextElement();
			Object value = Character_to_Location.get(key);
			System.out.println("Question/Answer Preview:  Where is "+key+" from in Fallout 2?         Answer : "+value);
		}
	    Random randomGenerator = new Random();
	    System.out.println("size: "+Character_to_Location.size());
	    System.out.println("___________________________________");
		//ask Ten randomized questions with 4 randomized answers
for( int i = 0 ; i  &lt; 10 ; i++)
{
	int randomInt = randomGenerator.nextInt(Character_to_Location.size());
	randomInt++;
	int iStop = 0;
	Enumeration morekeys = Character_to_Location.keys();
 
	while( morekeys.hasMoreElements() )
	{
	Object key = morekeys.nextElement();
	Object value = Character_to_Location.get(key);
	if ( iStop == randomInt)
	{
	//System.out.println("index:" + iStop + "    "+randomInt);
	System.out.println();
	System.out.println("Where is "+key+" from?");
	//Generate Multiple Choice
	//we know the correct answer is
	System.out.println("                   Correct Answer   : " + value);
	//now we need to generate other "incorrect" Choices
	//we need 3, Multiple Choice is Typically 4 questions
	LinkedList wrongAnswerList = new LinkedList();
	//while wrongAnswerList is not unique
	//we want to remove the possibility of duplicates
	//we want to not include correct answer
	boolean is_wronglist_unique = false;
 
while(!is_wronglist_unique)
{
int randomWrong = randomGenerator.nextInt(Character_to_Location.size());
randomWrong++;
Enumeration wrongkeys = Character_to_Location.keys();
int iStopInner =0;
while( wrongkeys.hasMoreElements() )
{
Object key2 = wrongkeys.nextElement();
Object value2 = Character_to_Location.get(key2);
if ( iStopInner == randomWrong)
{
if ( !wrongAnswerList.contains(value2))
{
if(!value2.equals(value))
	wrongAnswerList.add(value2);
}
 
}
iStopInner++;
}
if (wrongAnswerList.size() ==3)
{is_wronglist_unique = true;}
}
	System.out.println("                  Incorrect Answers : "+wrongAnswerList.toString());
	System.out.println();
	wrongAnswerList.add(value);
	System.out.println();
	String [] AnswerSet = (String[]) wrongAnswerList.toArray(new String[0]);
	//get 4 random ints :D
	//0-3
	LinkedList numberset = new LinkedList();
	boolean isnumbersetunique = false;
	int deerpCount = 0;
while(!isnumbersetunique)
{
int randomfinal4 = randomGenerator.nextInt(4);
if (!numberset.contains(randomfinal4))
{
	numberset.add(randomfinal4);
	deerpCount++;
}
if(deerpCount == 4)
{
isnumbersetunique = true;
String individualquestion ="";
System.out.println("** FINAL QUESTION ***   Where is "+key+" from?");
 individualquestion += "** FINAL QUESTION ***   Where is "+key+" from?";
ListIterator itr = numberset.listIterator();
String[] abcd = {"a.)","b.)","c.)","d.)"};
int ix = 0;
while(itr.hasNext())
{
	int get =(int) itr.next();
	System.out.println("                        " +abcd[ix]+" "+ AnswerSet[get]);
	individualquestion += "                        " +abcd[ix]+" "+ AnswerSet[get];
	ix++;
}
 
if ( !EveryPotentialQuestion_AnswerSet.contains(individualquestion))
{
	EveryPotentialQuestion_AnswerSet.add(individualquestion);
	//how do I know when this ^ is full ?????? ???????
	//What is the most optimal way to answer this ^ without doing it manually?
}
}
}
wrongAnswerList.clear();
		}
		iStop++;
	}
}
		//the more questions you ask the more answers you'll get
	}
}

Output Example:

What is the total number of distinct Questions and Possible combinations of Answers?  How many unique questions could be asked? Submit your answers below :D

C#: Hashtable Inversion, how to invert a Hashtable

This quick project is example of simple Data transformation.  Hashtable’s values containing a comma deliminated list of strings gets turned into a distinct list of keys in another Hashtable.  And, the numbers (keys of initial Hashtable) are accumulated into the values of the new Hashtable.  Creating an inverted Hashtable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
 
namespace HashInversion
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable num_2_Letters_Hash = new Hashtable();
            Hashtable letters_2_num_Hash = new Hashtable();
 
            num_2_Letters_Hash.Add(1, "a,c,d");
            num_2_Letters_Hash.Add(6, "d,e");
            num_2_Letters_Hash.Add(13, "a,d,j");
            num_2_Letters_Hash.Add(29, "c,e,d");
            num_2_Letters_Hash.Add(7, "j");
            num_2_Letters_Hash.Add(9, "e,c,a");
            num_2_Letters_Hash.Add(11, "c,d,f,j");
 
            foreach (var key in num_2_Letters_Hash.Keys)
            {
                string content = num_2_Letters_Hash[key].ToString();
                string [] letters = content.Split(',');
                for (int i = 0; i &lt; letters.Length; i++)
                {
                    if ( letters_2_num_Hash.ContainsKey(letters[i].ToString()))
                    {
                        string previous_content = letters_2_num_Hash[letters[i]].ToString();
                        letters_2_num_Hash[letters[i]] = previous_content + "," + key;
                    }
                    else
                    {
                        letters_2_num_Hash.Add(letters[i],""+key);
                    }
                }
            }
 
            Console.WriteLine();
 
            Console.WriteLine("before");
            foreach (var key in num_2_Letters_Hash.Keys)
            {Console.WriteLine(key + "   " + num_2_Letters_Hash[key]);}
 
            Console.WriteLine("after");
            foreach (var key in letters_2_num_Hash.Keys)
            {Console.WriteLine(key + "   " + letters_2_num_Hash[key]);}
        }
    }
}

Java: How to invert a Hashtable?

Say you have a Hashtable with : number for keys, and a comma deliminated list of letters of values.  Now you want to make another hash table which is the opposite.  The keys for the second Hashtable will be a distinct list of all possible letters from the first Hashtable, and the values will be a comma deliminated list of all the numbers associated with a particular letter.

import java.util.Enumeration;
import java.util.Hashtable;
 
public class HashInversion
{
	public static void main(String[] args)
	{
 
		//hashtable : numbers with lists of letters
		Hashtable num2letter_hash = new Hashtable();
 
		//hashtable letters with list of numbers
		Hashtable letters2num_hash = new Hashtable();
 
		num2letter_hash.put(1,"a,b,c,d");
		num2letter_hash.put(22,"g,e,d");
		num2letter_hash.put(73,"e,g,d");
		num2letter_hash.put(41,"a,v,c,d,b,e");
		num2letter_hash.put(5,"a,l");
		num2letter_hash.put(17,"a");
		num2letter_hash.put(18,"a,l,e");
 
		//loop through all the elements in num2letter_hash
		Enumeration keys = num2letter_hash.keys();
		while( keys.hasMoreElements() )
		{
int key = (int) keys.nextElement();
String content = (String) num2letter_hash.get(key);
//break up the content by commas
String [] letters = content.split(",");
for( int i = 0 ; i &lt; letters.length; i++)
{
//if this letter hasn't been added to the new hash,
//  add it, and set its value to the current key
//if it already exists in the new table, obtain the current value string
//  and append a new number/key to it.
if( letters2num_hash.containsKey(letters[i].toString()) )
{
String previous_num =  (String) letters2num_hash.get(letters[i].toString());
letters2num_hash.put(letters[i].toString(), previous_num+","+key);
}
else
{
letters2num_hash.put( letters[i].toString(), ""+key);
}
}
		}
		//before  (numbers,letter-list)
		System.out.println(num2letter_hash.toString());
		//after   (letters,number-list)
		System.out.println(letters2num_hash.toString());
	}
}

LOL! Big Data Analytics!

So what’s the best way to compare data?


Say you have a bunch of different data, of all different types and sizes.
You’ve got Square Data and Circle Data.

 

And Square Data is Different from Circle Data.
You know they are both Shapes, but one has 4 corners and the other has 0 corners.
“and thats ridiculous!” from either perspective.

Also, if we look closer we can see that circle data looks like this.

And Square Data looks like this.

Well, I can’t compare this “J” with “l” ! >:O


WHAT AN OUTRAGE!  This is very frustrating! >:<

. . .

But WHAT IF!  I had even more granular data about each J and l?

And ‘J’ looked like this.

And  ‘l’ looked like this.

:D!   Fantastic!  They have something in common!  COLORS !

“boring!”

meh, so now what? Well, we can record the frequency of each color related to each individual ‘J’ or ‘l’.

“so what?”

And then we can sort the color data of each J or l from most frequent to least.

“lame…”

“._.”

Then we can take the top x most frequent colors and call that a set (set of colors for each J and l).  So now, by putting emphasis on frequency we can attempt to make relevance!

“Whatever!”

We can now play with Data!

We can figure out and see what the most optimal algorithm for DataSet Comparison is!  Is it top 5 most frequent terms of “J” compared with the top 5 most frequent terms of “l” with at least 2 matches make a relation between “J” and “l”? Maybe its top 15 compared with the top 50 with x matches?  Maybe 5 vs. 15 with x matches?

If the colors were “special” words I find that the  top 10 vs. top 10 with 4 matches or more, works best.  But this could change at any moment!  I could wake up tomorrow and decide differently.  There is no absolute truth here,  teh absolute truth is in teh data!

:D

 

C#: How to read from Microsoft PowerPoint file ppt

Get the text out of each PowerPoint slide.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
 
namespace readPPT
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Office.Interop.PowerPoint.Application PowerPoint_App = new Microsoft.Office.Interop.PowerPoint.Application();
            Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
            Microsoft.Office.Interop.PowerPoint.Presentation presentation = multi_presentations.Open(@"C:\PPT\myPowerpoint.pptx");
            string presentation_text = "";
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                foreach (var item in presentation.Slides[i+1].Shapes)
                {
                    var shape = (PowerPoint.Shape)item;
                    if (shape.HasTextFrame == MsoTriState.msoTrue)
                    {
                        if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                        {
                            var textRange = shape.TextFrame.TextRange;
                            var text = textRange.Text;
                            presentation_text += text+" ";
                        }
                    }
                }
            }
            PowerPoint_App.Quit();
            Console.WriteLine(presentation_text);
        }
    }
}