lotrsimp12345 37 Posting Pro in Training

I am really confused as to how this works? You have a critique but where does the critique come in? Also is their a difference between activation on hidden nodes and output nodes? Does the critique come in during the hidden node? or the input node?
Thanks

lotrsimp12345 37 Posting Pro in Training

i am only filling in the top half of my my weight matrix.... so if the sum is greater than 0 I change the neuron to the oppossite otherwise i leave it the same?

lotrsimp12345 37 Posting Pro in Training

Added mouse listener it works whenever I click anywhere not only when I click on the circles

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hopfieldnet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;



public class hop2d extends JFrame{
    static final int MAXPATTERNS = 4;
    static final int ROWS = 8;                       // Dimensions of the images
    static final int COLS = 8;
    static final int MAINSCREEN = 0;        // Constants for drawing the screens
    static final int TRAINPATTS = 1;

    JButton viewTrainPattern;   // Click on this button to view the training patterns
    JButton singleStep;
    MyPanel patPanel ;// Click on this button to run a test one (more) step
    int trainPatterns[][][] = new int [MAXPATTERNS][COLS][ROWS];
    int testPattern[][] = new int [COLS][ROWS];
    int t[][][][] = new int [COLS][ROWS][COLS][ROWS];   // connection weights
    int screenMode = MAINSCREEN;

    public void init()
    {
        JFrame frame = new JFrame("Hopfield Net");
        JPanel panel = new JPanel();
        patPanel = new MyPanel(200, 300);
        JLabel panel1 = new JLabel();
        ItemHandler itemHandler = new ItemHandler();
        singleStep = new JButton("Single Step");
        viewTrainPattern = new JButton("View Train Pattern");
        singleStep.setSize(30, 15);
        viewTrainPattern.setSize(30,15);
        frame.setSize(600, 600);
        panel.setBounds(150, 100, 180 , 120);
        singleStep.addActionListener(itemHandler);
        viewTrainPattern.addActionListener(itemHandler);
        panel.add(singleStep);
        panel.add(viewTrainPattern);
        frame.getContentPane().add(panel, BorderLayout.NORTH);
        
        setupTrainingPatterns();
        // Initialise test pattern to blank
        for (int i = 0; i < COLS; i++)
            for (int j = 0; j < ROWS; j++)
                testPattern[i][j] = -1;
        panel1.setText(testPattern.toString());
        frame.getContentPane().add(patPanel, BorderLayout.CENTER);
        frame.setVisible(true);
    }



    public void setupTrainingPatterns ()
    {

        initialisePattern(0,"00000000","01111110","01000010","01000010","01000010","01000010","01111110","00000000");
        initialisePattern(1,"00000000","00010000","00010000","00010000","11111110","00010000","00010000","00010000");
        initialisePattern(2,"10011110","10010010","10010010","10010010","10010010","10010010","10010010","11110011"); …
lotrsimp12345 37 Posting Pro in Training

i have 2 panels because i have two windows...
The draw cell method creates a graphic object and i want to change color depending on if the graphic object is selected or not. I can't even create a handle to it.

lotrsimp12345 37 Posting Pro in Training

TITLE SHOULD ACTUALLY BE: how to get mouselistener to work on method in an class in java

If I click a circle it should change the color of the circle. But, I am having difficult getting it to work.
Help appreciated.

Main just calls this class and calls the init function.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hopfieldnet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.*;



public class hop2d extends JFrame{
    static final int MAXPATTERNS = 4;
    static final int ROWS = 8;                       // Dimensions of the images
    static final int COLS = 8;
    static final int MAINSCREEN = 0;        // Constants for drawing the screens
    static final int TRAINPATTS = 1;

    JButton viewTrainPattern;   // Click on this button to view the training patterns
    JButton singleStep;
    MyPanel patPanel ;// Click on this button to run a test one (more) step
    int trainPatterns[][][] = new int [MAXPATTERNS][COLS][ROWS];
    int testPattern[][] = new int [COLS][ROWS];
    int t[][][][] = new int [COLS][ROWS][COLS][ROWS];   // connection weights
    int screenMode = MAINSCREEN;

    public void init()
    {
        JFrame frame = new JFrame("Hopfield Net");
        JPanel panel = new JPanel();
        patPanel = new MyPanel(200, 300);
        JLabel panel1 = new JLabel();
        ItemHandler itemHandler = new ItemHandler();
        singleStep = new JButton("Single Step");
        viewTrainPattern = new JButton("View Train Pattern");
        singleStep.setSize(30, 15);
        viewTrainPattern.setSize(30,15);
        frame.setSize(600, 600);
        panel.setBounds(150, 100, 180 , 120);
        singleStep.addActionListener(itemHandler);
        viewTrainPattern.addActionListener(itemHandler);
        panel.add(singleStep);
        panel.add(viewTrainPattern);
        frame.getContentPane().add(panel, BorderLayout.NORTH);
        setupTrainingPatterns();
        // Initialise test pattern to blank
        for …
lotrsimp12345 37 Posting Pro in Training

thanks I got it to work.

lotrsimp12345 37 Posting Pro in Training

Trying to implement the learning algorithm but running into problems. How do I skip the value stored since I do not want to do calculations with it?

void Learn(int* weightmatrix, int* pattern, int numOfPatterns, int numOfNeurons){

	int skip[5]; //true means skip
	for(int patternNum = 1; patternNum <= numOfPatterns; patternNum++)
	{
		for(int neuronNum = 1; neuronNum <= numOfNeurons ; neuronNum++)
		{
			skip[5] = {false, false, false, false, false}; //reset
			skip[neuronNum-1] = true; 
			int sum = 0;
			for(int numOfConnectionsToANeuron = 1; numOfConnectionsToANeuron< (numOfNeurons - 1); numOfConnectionsToANeuron++)
			{
				for(int skipCounter = 0; skipCounter < numOfNeurons; skipCounter++)
				{
					if(skip[skipCounter] == false)
					{
						sum = (pattern[(neuronNum-1)* patternNum]* weight[]) + sum;
					}
					else if(skip[skipCounter] == true)
					{

					}
				}
			}
		}
	}
}
lotrsimp12345 37 Posting Pro in Training

I am trying to implement a hopfield net to learn patterns.

This is what I current have....

I am current having it create a random number of patterns based on the number of neurons

Next I am trying to make a weight matrix

Should I have a seperate weight matrix for every or is one good enough to apply the hebbs learning rule to? One should be enough since I know based on nodes how many it can recognize based on following formula: N/4 * log N, where N is numofNodes. it is log base 2?

Thanks.

#include <iostream>
#include <time.h>
#include <math.h>

using namespace std;

void randomlyCreatePatterns(int numOfNeurons, int numOfPatterns, int* pattern);
void createRandomWeightMatrix(int numOfNeurons, int numOfPatterns, int* weightmatrix, int* pattern);


int main (int argc, char *argv[])
{ 
    cout<<"Hopfield Artificial Neural Network (ANN):"<<endl<<endl;
    srand(time(NULL)); // use current time to seed random number generator
    int numOfNeurons = 5; // size of each pattern = number of neurons
	int* pattern = NULL;
	int numOfPatterns = 0;
	int* weightmatrix = NULL;
    //int columns,rows,k,sum;

    // Create random pattern matrix to learn, Each row is a separate pattern to learn (n bits each).
    cout<<"Training patterns:"<<endl<<endl;
    // max capacity (number of patterns it can learn) of Hopfield network N/4 * log(N)
    numOfPatterns = static_cast<int>((numOfNeurons/4)*(log10((double)numOfNeurons)/log10((double)2))); // number of patterns (rows)
	cout<<"Number of Patterns being stored is "<<numOfPatterns<<endl;
    pattern = new int[numOfPatterns * numOfNeurons];
	randomlyCreatePatterns(numOfNeurons, numOfPatterns, pattern);

	//Create and Print Out Weight Matrix
	weightmatrix = new int[numOfNeurons * numOfNeurons];
	createRandomWeightMatrix(numOfNeurons, numOfPatterns, …
lotrsimp12345 37 Posting Pro in Training

the only problem we have is that the ctrl-c doesn't work.

lotrsimp12345 37 Posting Pro in Training

This is due by tonight.... So, don't have enough time to start with threading. We seem to have the sleep on the third job queue working. The only problem is the ctrl-c. Ctrl-c is also the terminator for a process in UNIX. I think that may be the problem.

lotrsimp12345 37 Posting Pro in Training

please help. any suggestions.

lotrsimp12345 37 Posting Pro in Training

Any suggestions?

Here is the assignment:

Process Scheduling Project on

Write a C/C++ Process Scheduler program on UNIX to simulate the round robin priority scheduler with four queues: TASK_QUEUE, SERVER_QUEUE, POWER_USER_QUEUE, and USER_QUEUE.
The program should create the following processes (or threads) for the scheduler simulation:

1. The job-generation process (or thread) will randomly generate new jobs and put them into the job queues. The new jobs can be simple print and sleep/usleep operations.
The job queues may be stored in an external file so that it can be accessed by other process if processes are used (or store in an array of list if threads are used).

2. The scheduler process (or thread) will select a job from the job queues and create a new work process (or thread) to run the job. The scheduler will use the following scheduling algorithm:

a. Jobs in the TASK_QUEUE have the highest priority. These jobs will be run until finished.

b. Jobs in the SERVER_QUEUE have the second priority. These jobs will be run using the round robin algorithm.
(You should attach a random number from 1 to 3 with the job to indicate the number of quantum times that the job needed to be run to finish.)

c. Jobs in the POWER_USER_QUEUE have the third priority. These jobs will be run and then blocked for the input. It will become ready to run again when user types the interrupt key …

lotrsimp12345 37 Posting Pro in Training

Having problems with executing jobs using fork. The code is supposed to create one job and execute one job and repeat this multiple times. We are only supposed to use usleep in the jobgeneration() function.

We are having trouble sleeping and executing ctrl-c in the execute job function.

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
#include <map>
#include <signal.h>
#include <unistd.h>

using namespace std;

void jobScheduler();
void setJobQueues();
void jobGenerator(int maximumQueueSize);
int createRandomJob();
int createRandomQuatnumInteger();
int selectJob();
void executeJob(int jobnumber);
string convertInt(int number);

int main() {
	int pid; 
	int MAX_JOB_QUEUE_SIZE = 10;
	srand(time(0));
	// DONT UNCOMMENT SETJOBQUEUES!
	//setJobQueues(); //Set up the priority job queues with chosen file and data structure
	////////////////////////////////
	
	//jobGenerator(10);
	//selectJob();
	//jobScheduler();
	
	if(pid = fork() != 0){ //Parent, jobGenerator process
		cout<<":pid from if "<<pid<<endl;
		jobGenerator(MAX_JOB_QUEUE_SIZE); //generate random jobs and put them into priority queues. The priority queues must be protected in a critical region.
		//exit(0);
	}
	else{ //Child, job scheduler process
		cout<<":pid from else"<<pid<<endl;
		jobScheduler(); //schedule and execute the jobs
		exit(0);
	}
	
	//jobScheduler();
	return 1;
}

void setJobQueues(){
	ofstream file("queues.txt");
	file<<endl<<endl<<endl;
	file.close();
}

void jobGenerator(int maximumQueueSize){
	int number = 0;
	for(int i = 0; i<10; i++)
	{
		number = createRandomJob();
		string numberString = convertInt(number);
		cout<<"the number generated is "<<number<<endl;
		//cout<<"numberString="<<numberString<<endl;
		ifstream input;
		input.open("queues.txt", ifstream::in);
		
		string lineTask = "";
		string lineServer = "";
		string linePowerUser = "";
		string lineUser = "";
		
		int lineNumber = 0;
		getline(input, lineTask);
		getline(input, lineServer);
		getline(input, linePowerUser);
		getline(input, lineUser);
			
		/*cout<<"before\n";
		cout<<"line 1"<<lineTask<<endl;
		cout<<"line 2"<<lineServer<<endl;
		cout<<"line 3"<<linePowerUser<<endl;
		cout<<"line 4"<<lineUser<<endl;*/ …
lotrsimp12345 37 Posting Pro in Training
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Deployment;

namespace RegisteryCheck
{
    class Program
    {
        static void Main(string[] args)
        {
            ApplicationDeployment ab = new 

            

        }
    }
}
lotrsimp12345 37 Posting Pro in Training

thanks but I got it to work I created a class and created static members so that I can use the back, next and cancel buttons.

lotrsimp12345 37 Posting Pro in Training

Any suggestions. I am assuming I use a registery but i dont' know which member to use.
Thanks.

lotrsimp12345 37 Posting Pro in Training

Take line below which is in batch file and convert it in C# so that I don't have to create a seperate file. Thanks! Any suggestions? I have spent way too long on this.

Odbcconf /a {CONFIGDSN "Microsoft Access Driver (*.mdb)" "DSN=NexTest_CDMA_2009|Description=NexTest_CDMA_2009|DBQ=C:\prod\database\nextest_CDMA_2009.mdb"}

lotrsimp12345 37 Posting Pro in Training

Updated code

Following error: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

//set up database
                    OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();

                    builder.Driver = "Microsoft Access Driver (*.mdb)"; 
                    builder.Dsn = fileName.Substring(0, fileName.Length - 4); 
                    builder["Description"] = fileName.Substring(0, fileName.Length - 4); 
                    builder["DBQ"] = destFile;


                    System.Data.Odbc.OdbcConnection conn = new OdbcConnection(builder.ToString());

                    try
                    {
                        conn.Open();
                        // Process data here.
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Failed to connect to data source" + ex);
                    }
lotrsimp12345 37 Posting Pro in Training
//copy database files to target directory
            string fileName = "test.txt";
            string targetPath = StaticFormInstances.choose.txtbxTargetDir.Text;
            string sourcePath = @"\\il93fil48\3GSM\release\testapplication_REL_01_00_09\database";

            //Use Path Class to manipulate file and directory paths
            string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
            string destFile = System.IO.Path.Combine(targetPath, fileName);

            //Create a new target folder if it doesn't exist
            if (!System.IO.Directory.Exists(targetPath))
            {
                System.IO.Directory.CreateDirectory(targetPath);
            }

            if (System.IO.Directory.Exists(sourcePath))
            {
                string[] files = System.IO.Directory.GetFiles(sourcePath);

                //calculate total number of files in source
                int totalNumberOfFiles = files.Length;

                //current file number
                int fileNumber = 0;

                //create object to store database string
                OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();

                foreach (string s in files)
                {
                    //increase file number by 1
                    fileNumber++;

                    //copy file based on fileNumber
                    fileName = System.IO.Path.GetFileName(s);
                    destFile = System.IO.Path.Combine(targetPath, fileName);
                    System.IO.File.Copy(s, destFile, false);
                    
                    //set up database
                    
                    builder.Driver = "Microsoft Access Driver (*.mdb)";
                    builder.Dsn = fileName.Substring(0,fileName.Length - 4);
                    builder["Description"] = fileName.Substring(0, fileName.Length - 4);
                    builder["DBQ"] = destFile;
                    Console.WriteLine(builder.ConnectionString);
                    Console.WriteLine();

                    //clear current values and reset know keys to default
                    builder.Clear();

                    //calculate progess out of base of 100
                    int ProgressPercentage = (fileNumber / totalNumberOfFiles) * 100;

                    //update the progress bar
                    bckgrdSetUpDatabases.ReportProgress(ProgressPercentage);
                }
                
            }
lotrsimp12345 37 Posting Pro in Training

It doesn't seem to work. Compile error.

namespace Welcome
{
    public delegate string ReturnText();
    public partial class InstallingDlls : Form
    {
        public InstallingDlls()
        {
            InitializeComponent();
            bckgrdInstallDll.RunWorkerAsync();
        }

        private void bckgrdInstallDll_DoWork(object sender, DoWorkEventArgs e)
        {
            StaticFormInstances.dll.Invoke(new ReturnText(this.UpdateText));

            string fileName = "test.txt";
            string targetPath = StaticFormInstances.choose.txtbxTargetDir.Text;
            string sourcePath = @"\\il93fil48\3GSM\release\testapplication_REL_01_00_09\bin";

            //Use Path Class to manipulate file and directory paths
            string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
            string destFile = System.IO.Path.Combine(targetPath, fileName);

            //Create a new target folder if it doesn't exist
            if (!System.IO.Directory.Exists(targetPath))
            {
                System.IO.Directory.CreateDirectory(targetPath);
            }


            if (System.IO.Directory.Exists(sourcePath))
            {
                string[] files = System.IO.Directory.GetFiles(sourcePath);

                //calculate total number of files in source
                int totalNumberOfFiles = files.Length;

                //current file number
                int fileNumber = 0;

                //copy the files and overwrite destination files if they already exist
                foreach (string s in files)
                {
                    //increase file number by 1
                    fileNumber++;

                    //Use static Path methods to extract only the file name from the path.
                    fileName = System.IO.Path.GetFileName(s);
                    destFile = System.IO.Path.Combine(targetPath, fileName);
                    System.IO.File.Copy(s, destFile, true);

                    //calculate progess out of base of 100
                    int ProgressPercentage = (fileNumber/totalNumberOfFiles)*100;

                    //update the progress bar
                    bckgrdInstallDll.ReportProgress(ProgressPercentage);
                }
            }
            else
            {
                Console.WriteLine("Source path does not exist");
            }
        }

        private void bckgrdInstallDll_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            prgBarDll.Value = e.ProgressPercentage;
        }

        private void bckgrdInstallDll_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            StaticFormInstances.database = new Database();
            StaticFormInstances.database.Show();
            StaticFormInstances.dll.Hide();
        }
    }
}

namespace Welcome
{
    public partial class ChooseDirectory : Form
    {
        public ChooseDirectory()
        {
            InitializeComponent();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            StaticFormInstances.choose.Hide();
            StaticFormInstances.loc = new Location();
            StaticFormInstances.loc.Show();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            StaticFormInstances.wel.Dispose();
            StaticFormInstances.choose.Dispose();
        }

        private string UpdateText()
        { …
lotrsimp12345 37 Posting Pro in Training

I am not trying to update my value in another thread, I am trying to access it.

lotrsimp12345 37 Posting Pro in Training

Here is my code

public partial class InstallingDlls : Form
    {
        public InstallingDlls()
        {
            InitializeComponent();
            bckgrdInstallDll.RunWorkerAsync();
        }

        private void bckgrdInstallDll_DoWork(object sender, DoWorkEventArgs e)
        {
            //string text = StaticFormInstances.choose.txtbxTargetDir.Text.Substring(0, StaticFormInstances.choose.txtbxTargetDir.Text.IndexOf(@"\")) + StaticFormInstances.choose.txtbxTargetDir.Text.Substring(StaticFormInstances.choose.txtbxTargetDir.Text.IndexOf(@"\") + 1, StaticFormInstances.choose.txtbxTargetDir.Text.Length - (StaticFormInstances.choose.txtbxTargetDir.Text.IndexOf(@"\")));


            string fileName = "test.txt";
            string targetPath = StaticFormInstances.choose.txtbxTargetDir.Text;
            string sourcePath = @"\\il93fil48\3GSM\release\testapplication_REL_01_00_09\bin";

            //Use Path Class to manipulate file and directory paths
            string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
            string destFile = System.IO.Path.Combine(targetPath, fileName);

            //Create a new target folder if it doesn't exist
            if (!System.IO.Directory.Exists(targetPath))
            {
                System.IO.Directory.CreateDirectory(targetPath);
            }


            if (System.IO.Directory.Exists(sourcePath))
            {
                string[] files = System.IO.Directory.GetFiles(sourcePath);

                //calculate total number of files in source
                int totalNumberOfFiles = files.Length;

                //current file number
                int fileNumber = 0;

                //copy the files and overwrite destination files if they already exist
                foreach (string s in files)
                {
                    //increase file number by 1
                    fileNumber++;

                    //Use static Path methods to extract only the file name from the path.
                    fileName = System.IO.Path.GetFileName(s);
                    destFile = System.IO.Path.Combine(targetPath, fileName);
                    System.IO.File.Copy(s, destFile, true);

                    //calculate progess out of base of 100
                    int ProgressPercentage = (fileNumber/totalNumberOfFiles)*100;

                    //update the progress bar
                    bckgrdInstallDll.ReportProgress(ProgressPercentage);
                }
            }
            else
            {
                Console.WriteLine("Source path does not exist");
            }
        }

        private void bckgrdInstallDll_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            prgBarDll.Value = e.ProgressPercentage;
        }

        private void bckgrdInstallDll_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            StaticFormInstances.database = new Database();
            StaticFormInstances.database.Show();
            StaticFormInstances.dll.Hide();
        }
    }
lotrsimp12345 37 Posting Pro in Training

I still get the same exception. I think its because I am trying to access it in multiple forms. Maybe???
Btw I have each form set up as static so that I can add back button to it.


Heres the exception:
at Microsoft.VisualStudio.Debugger.Runtime.Main.ThrowCrossThreadMessageException(String formatString) at System.Windows.Forms.SafeNativeMethods.GetWindowTextLength(HandleRef hWnd) at System.Windows.Forms.Control.get_WindowText() at System.Windows.Forms.TextBoxBase.get_WindowText() at System.Windows.Forms.Control.get_Text() at System.Windows.Forms.TextBox.get_Text()

Please help.

lotrsimp12345 37 Posting Pro in Training

that doesn't work, it just adds the @ sign in front of the string and still keeps 2 \\

lotrsimp12345 37 Posting Pro in Training

I have set the textbox to public so that another form can access it but when i run it in debug mode with the following line it gives me exception so it doesn't store correct directory.
For example:
If I enter D:\newfolder it gives me D:\\newfolder. Why does it add the extra \.

Here's the exception:
An exception 'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException' occurred

Here's the line where the exception occurs.

Choose is a class in the same namespace as the method which contains this string.
The method is in a different class than the choose class.
txtbxTargetDir is the name of the textbox.

string targetPath = StaticFormInstances.choose.txtbxTargetDir.Text;
lotrsimp12345 37 Posting Pro in Training

I was wondering how you do this. Would you have to use delegates and event handlers or can you do it through application.Run(object) and call that in the clickevent but I need to keep a reference to previous form. but that doesn't seem possible.

lotrsimp12345 37 Posting Pro in Training

In the following code how to fix problem that the batch file won't get created. When I run in debug mode exception I get is "could not find part of path"

Thanks

StreamWriter sw = null;

            try
            {
                if (AgilentNVisaDriver.Checked == false && RequiredDlls.Checked == false)
                {
                    MessageBox.Show("Please select the application you would like to install");
                }
                else
                {
                    Assembly objAssembly = Assembly.GetAssembly(this.GetType());
                    string strAppPath = objAssembly.CodeBase;
                    strAppPath = strAppPath.Replace("SplashScreen.dll", "");
                    Uri objUri = new Uri(strAppPath);
                    strAppPath = @objUri.AbsolutePath;

                    string strBatchFilePath = strAppPath + @"Setup.bat";

                    sw = File.CreateText(strBatchFilePath);
lotrsimp12345 37 Posting Pro in Training

How to use bootstrapper manifest to create a prerequistie which runs another windows application installer before the setup.exe installer from the deployment project.
Thanks.

lotrsimp12345 37 Posting Pro in Training

how to have an executable run before deployment project executable?
Thanks

lotrsimp12345 37 Posting Pro in Training

it worked I wasn't typing the correct name.

lotrsimp12345 37 Posting Pro in Training

I have added a reference to dll file in VS 2008. Yet I still get an error. Not sure why, do I have to do some other changes to get it to work?

lotrsimp12345 37 Posting Pro in Training

Here's the assignment:
You are to create a single server (in either Java or C/C++) which can service both C/C++ and Java clients.

The protocol of the server is as follows:

1.  The client contacts the server.
2.  The client performs a single send of a data packet containing the following items (in the order specified):
a.  a 32-bit signed integer (int)
b.  a 64-bit floating point value (double)
c.  another 64-bit floating point value (double)
d.  another 32-bit signed integer (int)
e.  an array of 80 bytes representing a C char array 
(i.e. a C “string” – NOT a Java String or a C++ string, just
a character array with a null character (character 0) value to mark the end of the string)
3.  The server responds with a single data packet (a single send) containing:
a.  a 64-bit floating point value (double) 
the value of which should be a * cos(b) + sin(c) * d, where
a,b,c, and d are the values sent in the client packet above
b.  an array of 80 bytes representing a C char array
           the value of which should be the bytewise reversal of e in the
           client message.
           For example, if the client sends:
            “Hello World!”  (where ) represents the null character,
           the server should reply with:
            “!dlroW olleH”
           Note that the remainder of the byte array (after the first zero 
            byte) is to be ignored in both the client and the server messages.  (However, both must send a complete …
lotrsimp12345 37 Posting Pro in Training

how would you do that?

Language similar to LISP

I don't think you can use cons twice.

really stuck.

maybe
(define a '('()))

lotrsimp12345 37 Posting Pro in Training

so the problem was with the initialization of the arrays.
Here the answer
main.cpp

#include <iostream>
#include <ctime>
#include <stdio.h>
#include "Mastermind.h"

using namespace std;
 
int main()
{
	int* answer=new int[4];
	int populationsize=0;
	srand((unsigned)time(NULL));
	cout<<"please select 4 numbers out of the following options";
	cout<<"\nred:0\n"
		  "black:1\n"
		  "yellow:2\n"
		  "white:3\n"
		  "blue:4\n"
		  "green:5\n";
	for(int i=0; i<4; i++)
	{
		cin>>answer[i];
	}
	Mastermind a;
	a.setanswer(answer);
	cout<<"please enter a population size:\n";
	cin>>populationsize;
	a.setpopulationsize(populationsize);
	a.initializepopulation();
	a.calculatenumberofblackpegs();
	a.calculatenumberofwhitepegs();
	a.print();
	return 0;

}

mastermind.h

#include <iostream>
#include <cstdlib>

 
class Mastermind
{
public:
	Mastermind();
 
	void initializepopulation();
	void setpopulationsize(int populationsize);
	void setanswer(int* answer);
	void setgenerationnumber(int generationnumber);
	int randomizenumber();
 
	void calculatenumberofblackpegs();
	void calculatenumberofwhitepegs();
 
	void mutate();
	void crossover();
 
	void calculatepopulationfitness();
 
	int evaluatepopulation();
 
	void print();
 
private:
	int** population_;
	int populationsize_;
	int* answer_;
	int generationnumber_;
	int* totalnumberofblackpegs_;
	int* totalnumberofwhitepegs_;
	int* totalnumberofpegs_;
	int* fitness_;
	int sum(int index);
	int pickrandomposition();
	int** guess_pos;
	int** code_pos;
};

mastermind.cpp

#include "Mastermind.h"

 
Mastermind::Mastermind()
{
	populationsize_=0;
	answer_=new int[4];
	generationnumber_=0;
}
 
void Mastermind::initializepopulation()
{
	population_=new int*[populationsize_];
	for(int i=0; i<populationsize_; ++i)
	{
		population_[i]=new int[4];
	}
	for(int i=0; i<populationsize_; i++)
	{
		for(int j=0; j<4; j++)
		{
			population_[i][j]=randomizenumber();
		}
	}
	totalnumberofblackpegs_=new int[populationsize_];
	totalnumberofwhitepegs_=new int[populationsize_];
	totalnumberofpegs_=new int[populationsize_];
	fitness_=new int[populationsize_];
	guess_pos=new int*[populationsize_];
	for(int i=0; i<populationsize_; i++)
	{
		guess_pos[i]=new int[4];
	}
	code_pos=new int*[populationsize_];
	for(int m=0; m<populationsize_; ++m)
	{
		code_pos[m]=new int[4];
	}
	//initalize arrays
	for(int i=0; i<populationsize_; i++)
	{
		totalnumberofblackpegs_[i]=0;
		totalnumberofwhitepegs_[i]=0;
		totalnumberofpegs_[i]=0;
		for(int p=0; p<4; p++)
		{
			guess_pos[i][p]=3;
			code_pos[i][p]=3;
		} 
	}
}
 
void Mastermind::setpopulationsize(int populationsize)
{
	populationsize_=populationsize;
}
 
void Mastermind::setanswer(int* answer)
{
	answer_=answer;
}
 
void Mastermind::setgenerationnumber(int generationnumber)
{
	generationnumber_=generationnumber;
}
 
int Mastermind::randomizenumber()
{
	int d=rand()% 6; …
lotrsimp12345 37 Posting Pro in Training

kind of like this??

guess_pos=new (int*)[populationsize_];
	for(int i=0; i<populationsize_; ++i)
	{
		*(guess_pos[i])=new int[4];
	}

but that doesn't seem to work...

lotrsimp12345 37 Posting Pro in Training

starting to think that memory isn't big enough.

the totalnumberofpegs
i only set it to 0 in my code yet it changes it self somehow :(. please help
i have tried everything. It shows that it is 0 in all other functions.


main.cpp

#include <iostream>
#include <ctime>
#include <stdio.h>
#include "Mastermind.h"

using namespace std;
 
int main()
{
	int* answer=new int[4];
	int populationsize=0;
	srand((unsigned)time(NULL));
	cout<<"please select 4 numbers out of the following options";
	cout<<"\nred:0\n"
		  "black:1\n"
		  "yellow:2\n"
		  "white:3\n"
		  "blue:4\n"
		  "green:5\n";
	for(int i=0; i<4; i++)
	{
		cin>>answer[i];
	}
	Mastermind a;
	a.setanswer(answer);
	cout<<"please enter a population size";
	cin>>populationsize;
	a.setpopulationsize(populationsize);
	a.initializepopulation();
	a.calculatenumberofblackpegs();
	a.calculatenumberofwhitepegs();
	a.print();
	return 0;

}

mastermind.h

#include <iostream>
#include <cstdlib>
#define RIGHT_COLOR_RIGHT_POS       1
#define RIGHT_COLOR_WRONG_POS       2
#define WRONG_COLOR_WRONG_POS       3

 
class Mastermind
{
public:
	Mastermind();
 
	void initializepopulation();
	void setpopulationsize(int populationsize);
	void setanswer(int* answer);
	void setgenerationnumber(int generationnumber);
	int randomizenumber();
 
	void calculatenumberofblackpegs();
	void calculatenumberofwhitepegs();
 
	void mutate();
	void crossover();
 
	void calculatepopulationfitness();
 
	int evaluatepopulation();
 
	void print();
 
private:
	int** population_;
	int populationsize_;
	int* answer_;
	int generationnumber_;
	int* totalnumberofblackpegs_;
	int* totalnumberofwhitepegs_;
	int* totalnumberofpegs_;
	int* fitness_;
	int sum(int index);
	int pickrandomposition();
	int** guess_pos;
	int** code_pos;
};

mastermind.cpp

#include "Mastermind.h"

 
Mastermind::Mastermind()
{
	populationsize_=0;
	answer_=new int[4];
	generationnumber_=0;
	totalnumberofblackpegs_=new int[populationsize_];
	totalnumberofwhitepegs_=new int[populationsize_];
	totalnumberofpegs_=new int[populationsize_];
	fitness_=new int[populationsize_];
}
 
void Mastermind::initializepopulation()
{
	population_=(int**)(malloc(sizeof(int*)*populationsize_));
	for(int i=0; i<populationsize_; ++i)
	{
		*(population_+i)=(int*)(malloc(sizeof(int)*4));
	}
	for(int i=0; i<populationsize_; i++)
	{
		for(int j=0; j<4; j++)
		{
			population_[i][j]=randomizenumber();
		}
	}
}
 
void Mastermind::setpopulationsize(int populationsize)
{
	populationsize_=populationsize;
}
 
void Mastermind::setanswer(int* answer)
{
	answer_=answer;
}
 
void Mastermind::setgenerationnumber(int generationnumber)
{
	generationnumber_=generationnumber;
}
 
int Mastermind::randomizenumber()
{
	int d=rand()% …
lotrsimp12345 37 Posting Pro in Training

nvm figured it out. went to far in array index.

lotrsimp12345 37 Posting Pro in Training

so i think i know where the problem is...

it return garbage for code_pos even though i initalize and change values assigned to it. :( Please help.


but don't know how to fix it.

main.cpp

#include <iostream>
#include <ctime>
#include <stdio.h>
#include "Mastermind.h"

using namespace std;
 
int main()
{
	int* answer=new int[4];
	int populationsize=0;
	srand((unsigned)time(NULL));
	cout<<"please select 4 numbers out of the following options";
	cout<<"\nred:0\n"
		  "black:1\n"
		  "yellow:2\n"
		  "white:3\n"
		  "blue:4\n"
		  "green:5\n";
	for(int i=0; i<4; i++)
	{
		cin>>answer[i];
	}
	Mastermind a;
	a.setanswer(answer);
	cout<<"please enter a population size";
	cin>>populationsize;
	a.setpopulationsize(populationsize);
	a.initializepopulation();
	a.calculatenumberofblackpegs();
	a.calculatenumberofwhitepegs();
	a.print();
	return 0;

}

mastermind.h

#include <iostream>
#include <cstdlib>
#define RIGHT_COLOR_RIGHT_POS       1
#define RIGHT_COLOR_WRONG_POS       2
#define WRONG_COLOR_WRONG_POS       3

 
class Mastermind
{
public:
	Mastermind();
 
	void initializepopulation();
	void setpopulationsize(int populationsize);
	void setanswer(int* answer);
	void setgenerationnumber(int generationnumber);
	int randomizenumber();
 
	void calculatenumberofblackpegs();
	void calculatenumberofwhitepegs();
 
	void mutate();
	void crossover();
 
	void calculatepopulationfitness();
 
	int evaluatepopulation();
 
	void print();
 
private:
	int** population_;
	int populationsize_;
	int* answer_;
	int generationnumber_;
	int* totalnumberofblackpegs_;
	int* totalnumberofwhitepegs_;
	int* totalnumberofpegs_;
	int* fitness_;
	int sum(int index);
	int pickrandomposition();
	int** guess_pos;
	int** code_pos;
};

Mastermind.cpp

#include "Mastermind.h"

 
Mastermind::Mastermind()
{
	populationsize_=0;
	answer_=new int[4];
	generationnumber_=0;
	totalnumberofblackpegs_=new int[populationsize_];
	totalnumberofwhitepegs_=new int[populationsize_];
	totalnumberofpegs_=new int[populationsize_];
	fitness_=new int[populationsize_];
}
 
void Mastermind::initializepopulation()
{
	population_=(int**)(malloc(sizeof(int*)*populationsize_));
	for(int i=0; i<populationsize_; ++i)
	{
		*(population_+i)=(int*)(malloc(sizeof(int)*4));
	}
	for(int i=0; i<populationsize_; i++)
	{
		for(int j=0; j<4; j++)
		{
			population_[i][j]=randomizenumber();
		}
	}
}
 
void Mastermind::setpopulationsize(int populationsize)
{
	populationsize_=populationsize;
}
 
void Mastermind::setanswer(int* answer)
{
	answer_=answer;
}
 
void Mastermind::setgenerationnumber(int generationnumber)
{
	generationnumber_=generationnumber;
}
 
int Mastermind::randomizenumber()
{
	int d=rand()% 6;
	return d;
}

void Mastermind::calculatenumberofblackpegs()
{
	guess_pos=(int**)(malloc(sizeof(int*)*populationsize_));
	for(int …
lotrsimp12345 37 Posting Pro in Training

so... i decided to use object oriented programming approach seemed like it would be easier

Here's what I have so far incase any one has any ideas.

main.cpp

#include <iostream>

#include <stdio.h>
#include "population.h"
#include "Evolutionary Algorithm.h"


using namespace std;

int main()
{
	srand(NULL);

	//store code
	int answer[4];

	//store populationsize
	int populationsize;
	cout<<"please enter code\n";
	for(int i=0; i<4; i++)
	{
		cin>>answer[i];
	}
	cout<<"please enter a populationsize\n";
	cin>>populationsize;

	EvolutionaryAlgorithm b(populationsize);

	b.setanswer_(answer);

	//set population and print it out
	population a(populationsize);
	a.setpopulation();
	a.print();
	cout<<"total number of black\n";
	b.findpopulationblack(a);
	b.getblack();
	return 0;
}

position.h

#ifndef POSITION_H_INCLUDED
#define POSITION_H_INCLUDED

//#include <stdio.h>

class position
{
public:
	inline position()
	{
		position_=0;
	}

	inline void setposition(int pos)
	{
		position_=pos;
	}

	inline int getposition()
	{
		return position_;
	}

	inline int setranddata()
	{
		randdata_=rand()%6;
		return randdata_;
	}

	inline int getranddata()
	{
		return randdata_;
	}

private:
	int position_;

	int randdata_;
};

#endif;

individual.h

#ifndef INDIVIDUAL_H_INCLUDED
#define INDIVIDUAL_H_INCLUDED

#include "position.h"
#include <iostream>

using namespace std;

class individual
{
public:
	inline void setfirstposition(position one)
	{
		firstposition=one;
	}

	inline void setsecondposition(position two)
	{
		secondposition=two;
	}

	inline void setthirdposition(position three)
	{
		thirdposition=three;
	}

	inline void setfourthposition(position four)
	{
		fourthposition=four;
	}

	inline position getfirstposition()
	{
		return firstposition;
	}

	inline position getsecondposition()
	{
		return secondposition;
	}

	inline position getthirdposition()
	{
		return thirdposition;
	}

	inline position getfourthposition()
	{
		return fourthposition;
	}

	inline void setindivualposition()
	{
		firstposition.setposition(1);
		secondposition.setposition(2);
		thirdposition.setposition(3);
		fourthposition.setposition(4);
	}

	inline void setrandvalueforindivualposition()
	{
		firstposition.setranddata();
		secondposition.setranddata();
		thirdposition.setranddata();
		fourthposition.setranddata();
	}



private:
	//set positions
	position firstposition;
	position secondposition;
	position thirdposition;
	position fourthposition;

};


	ostream& operator …
lotrsimp12345 37 Posting Pro in Training

thanks. I think I agree I need to rewrite the function. I am trying to writing an evolutionary algorithm to solve the mastermind problem.

lotrsimp12345 37 Posting Pro in Training

It is impossible in C++ since you have to use iterator to erase.

Here's what I have:

main.ccp

#include <iostream>
#include <vector>
#include "Mastermind.h"

int main()
{
	vector<int>* answer=new vector<int>(4);
	cout<<"enter an code\n";
	for(int i=0; i<4; i++)
	{
		int k;
		cin>>k;
		answer->push_back(k);
	}
	//initalize population
	Mastermind a(5);
	//set answer
	a.setanswer(answer);
	a.showpopulation();
	a.evaluateblackandwhite();
	
	return 0;
}

Mastermind.h

#include <vector>
#include <string>

using namespace std;
class Mastermind
{
public:
	Mastermind(int populationsize);

	void showpopulation();

	void setanswer(vector<int>* answer);

	void evaluateblackandwhite();

	void calculatepopulationfitness();
	
	int evaluatepopulation();

	int	sum(int index);

	int randomizenumber();

private:
	int populationsize_;

	vector<int>* answer_;

	vector<vector<int>>* tempanswer_;

	vector<int>* fitness_;

	vector<vector<int>>* population_;

	vector<int>* totalnumberofpegs_;

	int* totalnumberofblackpegs_;

	int* totalnumberofwhitepegs_;

	//iterator through temp array


	//iterator through totalnumberofblackpegs
	vector<int>::iterator blackpegs;

	//iterator through totalnumberofwhitepegs
	vector<int>::iterator whitepegs;

	//iterate through population
	vector<vector<int>>::iterator pop;

	//iterate through individual
	vector<int>::iterator individual;

	vector<vector<string>>* feedback_;
};

/*inline bool operator ==(vector<string> a, string b)
{
	if(a==b)
	{
		return true;
	}
	else
	{
		return false;
	}
}*/

Mastermind.cpp

#include "Mastermind.h"
#include <iostream>

Mastermind::Mastermind(int populationsize)
{
	populationsize_=populationsize;
	population_=new vector<vector<int>>(populationsize_,NULL);
	for(int i=0; i<populationsize_; i++)
	{
		for(int j=0; j<4; j++)
		{
			population_->at(i).push_back(randomizenumber());
		}
	}
	answer_=new vector<int>(4);
	fitness_=new vector<int>(populationsize_);
	totalnumberofpegs_= new vector<int>(populationsize_);
	totalnumberofblackpegs_=new int[populationsize_];
	totalnumberofwhitepegs_=new int[populationsize_];
}

void Mastermind::showpopulation()
{
	for(pop=population_->begin(); pop!=population_->end(); ++pop)
	{
		for(individual=(*pop).begin(); individual!=(*pop).end(); ++individual)
		{
			cout<<*individual<<" ";
		}
		cout<<endl;
	}
}

void Mastermind::setanswer(vector<int>* answer)
{
	answer_=answer;
}

void Mastermind::evaluateblackandwhite()
{
	//copy answer to temp vector
	tempanswer_=new vector<vector<int>>(populationsize_,NULL);
	for(int i=0; i<populationsize_; i++)
	{
		for(int j=0; j<4; j++)
		{
			tempanswer_->at(i).push_back(answer_->at(j));
		}
	}

	//create feedback array
	feedback_=new vector<vector<string>>(populationsize_,NULL);
	for(int i=0; i<populationsize_; i++)
	{
		for(int j=0; j<4; j++)
		{ …
lotrsimp12345 37 Posting Pro in Training

problem is somewhere in this part of code.

for(int i=0; i<populationsize_; i++)
	{
		//check for black
		for(int j=answer_->front(); j!=answer_->back(); j++)
		{
			if(answer_[j]==population_[i][j])
			{
				feedback_[i][j].push_back("Match");
				for(int k=tempanswer_->at(i).front(); k!=tempanswer_->at(i).back(); k++)
				{
					//find first instance
					if(tempanswer_[i][k]==answer_[j])
					{
						tempanswer_[i][k].erase(tempanswer_->at(i).begin()+k);
						//erase data at that position
						break;
					}
				}
			}
		}
		//check for white(now go back and 
		//check for tempanswer but in wrong place
		/*for(int l=population_->at(i).front(); l<population_->at(i).back(); l++)
		{
			if(feedback_->at(i).at(l)=="")
			{
				for(int m=0; m<tempanswer_[i].size(); m++)
				{
					if(population_[i][l]==tempanswer_[i][m])
					{
						feedback_[i][l].push_back("Present");
						tempanswer_[i].erase(tempanswer_[i].begin()+m);
						break;
					}
				}
			}
		}
		
		//tally up feedback
		for(int a=0; a<feedback_[i].size(); a++)
		{
			if(feedback_[i][a]=="Match")
			{
				totalnumberofblackpegs_[i]++;
			}
			else if(feedback_[i][a]=="Present")
			{
				totalnumberofwhitepegs_[i]++;
			}
			else
			{
				totalnumberofwhitepegs_[i]=totalnumberofwhitepegs_[i];
				totalnumberofblackpegs_[i]=totalnumberofblackpegs_[i];
			}
		}
		
	}
	std::cout<<"after\n";
	for(int p=0; p<populationsize_; p++)
	{
		cout<<totalnumberofblackpegs_[p];
	}*/
lotrsimp12345 37 Posting Pro in Training

its doesn't like me doing matching for some reason when it is declared as a string at the end where I of the blackandwhite method.

problem is with evaluate black and white method.

lotrsimp12345 37 Posting Pro in Training

Here is all of my code: Now I get stack error. :(.

Main.cpp

#include <iostream>
#include <vector>
#include "Mastermind.h"

int main()
{
	vector<int>* answer=new vector<int>(4);
	cout<<"enter an code\n";
	for(int i=0; i<4; i++)
	{
		int k;
		cin>>k;
		answer->push_back(k);
	}
	//initalize population
	Mastermind a(5);
	//set answer
	a.setanswer(answer);
	a.showpopulation();
	a.evaluateblackandwhite();
	
	return 0;
}

Mastermind.h

#include <vector>
#include <string>

using namespace std;
class Mastermind
{
public:
	Mastermind(int populationsize);

	void showpopulation();

	void setanswer(vector<int>* answer);

	void evaluateblackandwhite();

	void calculatepopulationfitness();
	
	int evaluatepopulation();

	int	sum(int index);

private:
	int populationsize_;

	vector<int>* answer_;

	vector<vector<int>>* tempanswer_;

	vector<int>* fitness_;

	vector<vector<int>>* population_;

	vector<int>* totalnumberofpegs_;

	int* totalnumberofblackpegs_;

	int* totalnumberofwhitepegs_;

	//iterator through temp array


	//iterator through totalnumberofblackpegs
	vector<int>::iterator blackpegs;

	//iterator through totalnumberofwhitepegs
	vector<int>::iterator whitepegs;

	//iterate through population
	vector<vector<int>>::iterator pop;

	//iterate through individual
	vector<int>::iterator individual;

	vector<vector<string>>* feedback_;

	int randomizenumber();
};

inline bool operator ==(vector<string> a, string b)
{
	if(a==b)
	{
		return true;
	}
	else
	{
		return false;
	}
}

Mastermind.cpp

#include "Mastermind.h"
#include <iostream>

Mastermind::Mastermind(int populationsize)
{
	populationsize_=populationsize;
	population_=new vector<vector<int>>(populationsize_,NULL);
	for(int i=0; i<populationsize_; i++)
	{
		for(int j=0; j<4; j++)
		{
			population_->at(i).push_back(randomizenumber());
		}
	}
	answer_=new vector<int>(4);
	fitness_=new vector<int>(populationsize_);
	totalnumberofpegs_= new vector<int>(populationsize_);
	totalnumberofblackpegs_=new int[populationsize_];
	totalnumberofwhitepegs_=new int[populationsize_];
}

void Mastermind::showpopulation()
{
	for(pop=population_->begin(); pop!=population_->end(); ++pop)
	{
		for(individual=(*pop).begin(); individual!=(*pop).end(); ++individual)
		{
			cout<<*individual<<" ";
		}
		cout<<endl;
	}
}

void Mastermind::setanswer(vector<int>* answer)
{
	answer_=answer;
}

void Mastermind::evaluateblackandwhite()
{
	//copy answer to temp vector
	tempanswer_=new vector<vector<int>>(populationsize_,NULL);
	for(int i=0; i<populationsize_; i++)
	{
		for(int j=0; j<4; j++)
		{
			tempanswer_->at(i).push_back(answer_->at(j));
		}
	}
	//create feedback array
	feedback_=new vector<vector<string>>(populationsize_,NULL);
	for(int i=0; i<populationsize_; i++)
	{
		for(int j=0; j<4; j++)
		{
			feedback_->at(i).push_back("");
		}
	}

	for(int i=0; i<populationsize_; …
lotrsimp12345 37 Posting Pro in Training

Here's my code when I change it. Get 8 errors for this part alone. :(

for(int i=0; i<populationsize_; i++)
{
    //check for black
    for(individual=answer_->begin(); individual!=answer_->end(); individual++)
    {
        if(answer_->at(individual)==population_->at(i).at(individual))
        {
            feedback_[i][individual].push_back("Match");
            for(vector<int>::iterator itr=tempanswer_->at(i).begin(); itr!=tempanswer_->at(i).back(); itr++)
            {
                //find first instance
                if(tempanswer_[i][itr]==answer_[individual])
                {
                    tempanswer_[i].erase(itr);
                    break;
                }
            }
        }
    }
}

Errors are:

Error 1 error C2664: 'const int &std::vector<_Ty>::at(unsigned int) const' : cannot convert parameter 1 from 'std::_Vector_iterator<_Ty,_Alloc>' to 'unsigned int' c:\users...\documents\visual studio 2008\projects\cs 561\mastermind\mastermind\mastermind.cpp 65 Mastermind
Error 2 error C2664: 'const int &std::vector<_Ty>::at(unsigned int) const' : cannot convert parameter 1 from 'std::_Vector_iterator<_Ty,_Alloc>' to 'unsigned int' c:\users...\documents\visual studio 2008\projects\cs 561\mastermind\mastermind\mastermind.cpp 65 Mastermind
Error 3 error C2679: binary '[' : no operator found which takes a right-hand operand of type 'std::_Vector_iterator<_Ty,_Alloc>' (or there is no acceptable conversion) c:\users...\documents\visual studio 2008\projects\cs 561\mastermind\mastermind\mastermind.cpp 67 Mastermind
Error 4 error C2228: left of '.push_back' must have class/struct/union c:\users...\documents\visual studio 2008\projects\cs 561\mastermind\mastermind\mastermind.cpp 67 Mastermind
Error 5 error C2679: binary '!=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion) c:\users...\documents\visual studio 2008\projects\cs 561\mastermind\mastermind\mastermind.cpp 68 Mastermind
Error 6 error C2679: binary '[' : no operator found which takes a right-hand operand of type 'std::_Vector_iterator<_Ty,_Alloc>' (or there is no acceptable conversion) c:\users...\documents\visual studio 2008\projects\cs 561\mastermind\mastermind\mastermind.cpp 71 Mastermind
Error 7 error C2677: binary '[' : no global operator found which takes type 'std::_Vector_iterator<_Ty,_Alloc>' (or there is no acceptable conversion) c:\users...\documents\visual studio 2008\projects\cs 561\mastermind\mastermind\mastermind.cpp 71 Mastermind
Error 8 error C2664: 'std::_Vector_iterator<_Ty,_Alloc> std::vector<_Ty>::erase(std::_Vector_const_iterator<_Ty,_Alloc>)' : cannot convert …

lotrsimp12345 37 Posting Pro in Training

When i try it goes heywire and gives me 35 errors. all for the erase command. :(

for(int i=0; i<populationsize_; i++)
	{
		//check for black
		for(int j=answer_->front(); j!=answer_->back(); j++)
		{
			if(answer_[j]==population_[i][j])
			{
				feedback_[i][j].push_back("Match");
				for(int k=tempanswer_->at(i).front(); k!=tempanswer_->at(i).back(); k++)
				{
					//find first instance
					if(tempanswer_[i][k]==answer_[j])
					{
						tempanswer_[i].erase(k);
						break;
					}
				}
			}
		}
}
lotrsimp12345 37 Posting Pro in Training

So I tried your way....
It works for 90% of them

It doesn't work for some of them. answer i enter
is=1232 it gives.... W|B|Total
3131 1 |2|3
2131 1 |1|2

void Mastermind::getblackpegs()
{
	//allocate array
	tempanswer_=(int**)(malloc(sizeof(int*)*populationsize_));
	for(int i=0; i<populationsize_; ++i)
	{
		*(tempanswer_+i)=(int*)(malloc(sizeof(int)*4));
	}

	//copy data
	for(int k=0; k<populationsize_; k++)
	{
		for(int j=0; j<4; j++)
		{
			tempanswer_[k][j]=answer_[j];
		}
	}

	//test for black
	for(int k=0; k<populationsize_; k++)
	{
		for(int j=0; j<4; j++)
		{
			if(population_[k][j]==tempanswer_[k][j])
			{
				totalnumberofblackpegs_[k]++;
				tempanswer_[k][j]=-1;  //answer code is found don't reuse
				population_[k][j]=-2; //guess has been used, don't reuse
			}
		}
	}
}

void Mastermind::getwhitepegs()
{
	for(int k=0; k<populationsize_; k++)
	{
		//go through tempanswer array
		for(int j=0; j<4; j++)
		{
			//go through guesses
			for(int i=0; i<4; i++)
			{	
				//not already accounted and 
				if((population_[k][j]==tempanswer_[k][i]))//&&population_[k][j]!=-2&&tempanswer_[k][j]!=-1)
				{
					tempanswer_[k][j]=-1;  //answer is found don't reuse
					population_[k][j]=-2; //guess has been used, don't reuse
					totalnumberofwhitepegs_[k]++;
				}
				else
				{
					totalnumberofwhitepegs_[k]=totalnumberofwhitepegs_[k];
				}
			}
		}
	}
}

void Mastermind::gettotalnumberofpegs()
{
	for(int k=0; k<populationsize_; k++)
	{
		totalnumberofpegs_[k]=totalnumberofblackpegs_[k]+totalnumberofwhitepegs_[k];
	}
}
lotrsimp12345 37 Posting Pro in Training

the temp version of array is replaced by bool one in my code. So the temp version of answer will store which ever ones don't contain black?? Anyways I am off to sleep. Have a week to finish up this code.

lotrsimp12345 37 Posting Pro in Training

that's exactly what i am doing here...

if(population_[k][j]==answer_[i])

you need the && condition so that you don't double count.

The second array is necessary to say that already accounted in black so don't account it again.... since you don't want the total of black and white to be greater than 4.

in regards to the second comment, i don't care about positions, i care about number of white and blacks.

lotrsimp12345 37 Posting Pro in Training

WaltP your way doesn't even work... you need the 2nd array to say where you already guessed that position or not.