• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Well, yes, but I think he expect something else, but I can't find what...

No, that's pretty much what I expected. I said it was an asshole pedantic question didn't i? :) You said you can only call free once on any pointer returned from malloc, I said there's an exception. A useless exception that never matters obviously, just something to impress your friends with when playing Cards Against Compilers or something, I guess.
 

Koren

Member
lol!

And I said right of the bat that freeing Null was safe. Too obvious...

Is a sense, I prefer this, I thought there was something I was doing wrong.
 

Somnid

Member
I am working on a c# application which records global mouse clicks/touches. Start and Stop buttons are used to for each recording. The time and date of the recording start and stop time is logged and every mouse click/touch during the recording is captured.

I am using a listBox for the recording collection and another listBox to show the coords and times of each click.

I have a RecordingData list and a TouchData list as shown below,
TouchData is a nested list of touches within each recording, this is the root of my problem.

So my Recording Data is all captured correctly and showing correctly in the listbox. The mouse information is also being captured, however, it is not splitting up the mouse click data into each recording. If recording one captures 3 mouse clicks and recording 2 captures 7 mouse clicks, the listbox is showing 10 mouse clicks for the first recording.


My apologies if this is very confusing. Feedback welcome as I am a beginner in C#.

There is one global reference to a touchData and you just add that reference to the recordingData. So you keep changing it and it changes every place it's referenced. You need to create a "new" one each time you start a recording.
 

Two Words

Member
My university's UNIX course is oddly put together. The CS1 class you take before you take UNIX used to be taught in Java and the UNIX class was supposed to introduce you to more complex C/C++ stuff. But the CS1 class has been changed to C++ for a few semesters now. So the UNIX class is still spending a lot of time teaching what was already taught. I guess it makes for an easy grade at least :p



Speaking on that, I had a disagreement on a test question. How would you answer this question?


To dereference a structure pointer, use the __ operator.

A: *
B: &
C: <-
D: ->

I said A, but D was what was the correct answer on the test.
 

blueweltall

Neo Member
I have an technical interview for an intern software position coming up. What types of question should I study for? I have never done a technical interview before. I applied for a position that is looking for C++ background if that helps.
 
OK so remember thant advent of code thingy? I'm stuck at tday 5 and have no clue what I'm doing wrong.
Heres what's being asked of me:
Santa needs help figuring out which strings in his text file are naughty or nice.

A nice string is one with all of the following properties:

It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou.
It contains at least one letter that appears twice in a row, like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd).
It does not contain the strings ab, cd, pq, or xy, even if they are part of one of the other requirements.

For example:

ugknbfddgicrmopn is nice because it has at least three vowels (u...i...o...), a double letter (...dd...), and none of the disallowed substrings.
aaa is nice because it has at least three vowels and a double letter, even though the letters used by different rules overlap.
jchzalrnumimnmhp is naughty because it has no double letter.
haegwjzuvuyypxyu is naughty because it contains the string xy.
dvszwmarrgswjxmb is naughty because it contains only one vowel.

How many strings are nice?
Note that the file contains 1000 unique random strings of letters, and only letters. If someone's interested, I can pass the list around.
Here's my code: http://pastebin.com/pibcUxrF I used Java. My answer was 165 which, apparently, is wrong. Looking at the resulting strings, they all looked legit, so chances are I'm somehow missing some somewhere along the line. I can't figure where, though :/
 

peakish

Member
OK so remember thant advent of code thingy? I'm stuck at tday 5 and have no clue what I'm doing wrong.
Heres what's being asked of me:

Note that the file contains 1000 unique random strings of letters, and only letters. If someone's interested, I can pass the list around.
Here's my code: http://pastebin.com/pibcUxrF I used Java. My answer was 165 which, apparently, is wrong. Looking at the resulting strings, they all looked legit, so chances are I'm somehow missing some somewhere along the line. I can't figure where, though :/
I'm not very familiar with Java, but I figure that HashSet is a set? Maybe some strings collide and overwrite each other when you add them, or would Java raise a warning for that?
 

dabig2

Member
OK so remember thant advent of code thingy? I'm stuck at tday 5 and have no clue what I'm doing wrong.
Heres what's being asked of me:

Note that the file contains 1000 unique random strings of letters, and only letters. If someone's interested, I can pass the list around.
Here's my code: http://pastebin.com/pibcUxrF I used Java. My answer was 165 which, apparently, is wrong. Looking at the resulting strings, they all looked legit, so chances are I'm somehow missing some somewhere along the line. I can't figure where, though :/

Does the generated file contain a mix of capitals and lowercase letters? If it's a mix, then your code won't pick up all of the matches. I would transform the string you read from the file to all lowercase before running your passes.

I'm not very familiar with Java, but I figure that HashSet is a set? Maybe some strings collide and overwrite each other when you add them, or would Java raise a warning for that?

A Hashset does operate like a regular set. No error is raised, but the add method does return a boolean which will let you know if the addition worked or not. So you'll get a false if the object is already in the set.
 

Koren

Member
Note that the file contains 1000 unique random strings of letters, and only letters. If someone's interested, I can pass the list around.
Before looking into details, is the list unique for each user?

I just tried, I have more than 200 strings that fits the criteria, and there's not a single duplicate.

(And hell, for all I'm not overly fond of Python for very large projects, it's sure handy for this kind of problems that can be solved in a single line...)
 
Before looking into details, is the list unique for each user?

I just tried, I have more than 200 strings that fits the criteria, and there's not a single duplicate.

(And hell, for all I'm not overly fond of Python for very large projects, it's sure handy for this kind of problems that can be solved in a single line...)

yes, the list is unique for each user. I'm doing it with a friend that uses python and our sources/answers are different. And yeah, he does make it look easy with python lol...
Does the generated file contain a mix of capitals and lowercase letters? If it's a mix, then your code won't pick up all of the matches. I would transform the string you read from the file to all lowercase before running your passes.
I forgot to mention it, but all the letters are lower case.

I use a set because of the way I check for matches in the string: if there are multiple matches in a single string then I would get one or more duplicates of that string. Putting the results in a set deletes the duplicates automagically. It's just simpler that way.
 

peakish

Member
yes, the list is unique for each user. I'm doing it with a friend that uses python and our sources/answers are different. And yeah, he does make it look easy with python lol...

I forgot to mention it, but all the letters are lower case.

I use a set because of the way I check for matches in the string: if there are multiple matches in a single string then I would get one or more duplicates of that string. Putting the results in a set deletes the duplicates automagically. It's just simpler that way.
If you don't mind, could you upload the input? I could run it through my version to see what I get.
 

Koren

Member
I use a set because of the way I check for matches in the string: if there are multiple matches in a single string then I would get one or more duplicates of that string. Putting the results in a set deletes the duplicates automagically. It's just simpler that way.
Why not testing each line 1 by 1 to check whether they fits the requirements, and use a simple counter?

And, btw, you've just killed my productivity at the worst time... I just did both tasks of the first 5 days... I've heard about this website some time ago, but I carefully avoided it for now. Now, I'm doomed. ^_^
 
Why not testing each line 1 by 1 to check whether they fits the requirements, and use a simple counter?

And, btw, you've just killed my productivity at the worst time... I just did both tasks of the first 5 days... I've heard about this website some time ago, but I carefully avoided it for now. Now, I'm doomed. ^_^

A more immediate solution would be to break out of the loop as soon as I get a match :D Or are you talking about the final series of strings? I could do that, but on a cursory glance they all look like they fit the criteria.
 

P44

Member
Guys what's a good way to debug PHP on the sort of level of console statement type debugging/print statements etc.
 

peakish

Member
A more immediate solution would be to break out of the loop as soon as I get a match :D Or are you talking about the final series of strings? I could do that, but on a cursory glance they all look like they fit the criteria.
Maybe this is just me not knowing Java, but aren't you already breaking out of the loops as soon as a match is found? So for each string you already seem to be only getting a single string (or null) returned.

What I think could be more obvious is if you return either true or false instead of the string once a match is (or isn't) found, then there's no risk whatsoever of returning a duplicate from within the string. Instead, if all three functions return true you can simply add the string to the list.

This is basically what I'm doing, anyway, although in a functional form. My program gives 236 as the answer with your input, although of course I can't be sure that's correct since I can't try it... it works for my input, at least :p
 
Maybe this is just me not knowing Java, but aren't you already breaking out of the loops as soon as a match is found? So for each string you already seem to be only getting a single string (or null) returned.

What I think could be more obvious is if you return either true or false instead of the string once a match is (or isn't) found, then there's no risk whatsoever of returning a duplicate from within the string. Instead, if all three functions return true you can simply add the string to the list.

This is basically what I'm doing, anyway, although in a functional form. My program gives 236 as the answer with your input, although of course I can't be sure that's correct since I can't try it... it works for my input, at least :p

Yeah your answer was right :p
And no, the way my loop works is that it goes through all the letters to match (aa, bb, cc and so on) and returns a string every time one of those is found inside the string.
idk I'll try to work on my loops a bit and see where exactly I went wrong. Let's try doing it your way.
 

luoapp

Member
OK so remember thant advent of code thingy? I'm stuck at tday 5 and have no clue what I'm doing wrong.
Heres what's being asked of me:

Note that the file contains 1000 unique random strings of letters, and only letters. If someone's interested, I can pass the list around.
Here's my code: http://pastebin.com/pibcUxrF I used Java. My answer was 165 which, apparently, is wrong. Looking at the resulting strings, they all looked legit, so chances are I'm somehow missing some somewhere along the line. I can't figure where, though :/

ok, post your file somewhere. I need to pick up my reg exp skills.
 

gundalf

Member
I am currently trying to learn Javascript and node.js with this tutorial: https://github.com/maxogden/art-of-node#callbacks]

I am on the 4. lecture "my fist sync i/o" and I don't understand why the callback of fs.readFile only works with anonymous functions. Isn't it possible to use a function which I have declared beforehand?

This gives me the error that err is not defined
Code:
var fs = require("fs");
var pathArg  = process.argv[2];

function printLineCount(err, text){
	var lineCount = text.split("\n").length -1;
	console.log(lineCount);
}

//Invoking declared function = Error!
fs.readFile(pathArg, "utf8", printLineCount(err, data));

Returns Error:
fs.readFile(pathArg, "utf8", printLineCount(err, data));
ReferenceError: err is not defined

But invoking printLineCount from an anon function works!
Code:
var fs = require("fs");
var pathArg  = process.argv[2];

function printLineCount(text){
	var lineCount = text.split("\n").length -1;
	console.log(lineCount);
}

//Anonymous Function works!
fs.readFile(pathArg, "utf8", (err, data) => {
	printLineCount(data);
});

//Lambda expression also works!
fs.readFile(pathArg, "utf8", (err, data) => {
	printLineCount(data);
});
 
ok, post your file somewhere. I need to pick up my reg exp skills.

Will do, but if you use regex please share your solution, because I tried doing it that way but couldn't get it right at all (never used regex before).

Here's the gdrive link below quote this post to see it!
 

peakish

Member
Yeah your answer was right :p
And no, the way my loop works is that i goes through all the letters to match (aa, bb, cc and so on) and returns a string everytime one of those is found inside the string.
idk I'll try to work on my loops a bit and see where exactly I went wrong. Let's try doing it your way.
Ah, I see. I checked your input to see if there were any duplicates and there weren't, so my original theory is out the window either way.

Have you tried writing any tests? I've solved all of the AOC entries (up to 7, where I'm at currently) by implementing tests for all the input string examples given in the exercise, and once I pass all of them I tend to pass the final input immediately. Tests put me in a state of always knowing exactly what the important functions return which is pretty great for this.
 
I am currently trying to learn Javascript and node.js with this tutorial: https://github.com/maxogden/art-of-node#callbacks]

I am on the 4. lecture "my fist sync i/o" and I don't understand why the callback of fs.readFile only works with anonymous functions. Isn't it possible to use a function which I have declared beforehand?

This gives me the error that err is not defined
Code:
var fs = require("fs");
var pathArg  = process.argv[2];

function printLineCount(err, text){
	var lineCount = text.split("\n").length -1;
	console.log(lineCount);
}

//Invoking declared function = Error!
fs.readFile(pathArg, "utf8", printLineCount(err, data));

Returns Error:


But invoking printLineCount from an anon function works!
Code:
var fs = require("fs");
var pathArg  = process.argv[2];

function printLineCount(text){
	var lineCount = text.split("\n").length -1;
	console.log(lineCount);
}

//Anonymous Function works!
fs.readFile(pathArg, "utf8", (err, data) => {
	printLineCount(data);
});

//Lambda expression also works!
fs.readFile(pathArg, "utf8", (err, data) => {
	printLineCount(data);
});

Just call fs.readFile(pathArg, "utf8", printLineCount); and the arguments will be passed automatically.
 

Koren

Member
Will do, but if you use regex please share your solution, because I tried doing it that way but couldn't get it right at all (never used regex before).
Which regexp syntax?

For example, this line:
Code:
cat data.txt | egrep '([aeiou].*){3}' | egrep '(.)\1' | egrep -v -c 'ab|cd|pq|xy'
returns the number of lines fitting the criterias in data.txt.

Edit: I'm wondering whether I could solve the 25 "levels" using 25 different tools/languages... Seems an interesting challenge, at least.
 
Which regexp syntax?

For example, this line:
Code:
cat data.txt | egrep '([aeiou].*){3}' | egrep '(.)\1' | egrep -v -c 'ab|cd|pq|xy'
returns the number of lines fitting the criterias in data.txt.

Edit: I'm wondering whether I could solve the 25 "levels" using 25 different tools/languages... Seems an interesting challenge, at least.

I used this guide, among others: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html#introduction_regexexamples

edit: btw using String.matches("([aeiou].*){3}") already return a number of string inferior to the right answer (153 vs over 200) so uhh...
 

luoapp

Member
Will do, but if you use regex please share your solution, because I tried doing it that way but couldn't get it right at all (never used regex before).

Here's the gdrive link below quote this post to see it!

Can't do better than Koren's answer. Just FYI,
n=236
I tried on a Mac.


I read through your java code. thirdPass doesn't seem right, it'll miss substrings like "aaa", "aae", etc. Should loop through characters in s.

Code:
   public static String thirdPass(String s) {
        int voc = 0;
        for (String v : vocali) {
 
            if (s.contains(v)) {
                voc++;
 
                if (voc >= 3) {
                    voc = 0;
                    return s;
                }
 
            }
        }
 
        return null;
 

Koren

Member
I used this guide, among others: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html#introduction_regexexamples

edit: btw using String.matches("([aeiou].*){3}") already return a number of string inferior to the right answer (153 vs over 200) so uhh...
I'm not familiar with Strings.matches syntax, and regex syntax change depending on the tools, but I'm positive the line above give the good result (I've checked with my own set).

Edit: just checked with yours, and I got more than 200 for all three criteria.

According to this:
http://stackoverflow.com/questions/4450045/difference-between-matches-and-find-in-java-regex

String.matches assume a ^ at the beginning of the regex, so you probably want to add .* before, I guess...

String.matches(".*([aeiou].*){3}")

I'm also not sure you can write "(.)\1" with String.matches, you probably have to rewrite it with look ahead capabilities...
 
I'm not familiar with Strings.matches syntax, and regex syntax change depending on the tools, but I'm positive the line above give the good result (I've checked with my own set).

Edit: just checked with yours, and I got more than 200 for all three criteria.

According to this:
http://stackoverflow.com/questions/4450045/difference-between-matches-and-find-in-java-regex

String.matches assume a ^ at the beginning of the regex, so you probably want to add .* before, I guess...

String.matches(".*([aeiou].*){3}")

I'm also not sure you can write "(.)\1" with String.matches, you probably have to rewrite it with look ahead capabilities...
Yep, that was it. thanks to luoapp as well: the error was indeed in thirdPass. Using (".*([aeiou].*){3}") gave me the right answer. Onto the next problem!
 

Two Words

Member
I've got a question about forking and piping in C. I have a project where the parent makes 10 children. Each child only writes to the parent and the parent only reads from the child. From what I've heard, it is possible (but very rare) for my parent to read from the child while my child is still in the middle of writing to the parent, and causing for the read to be a read of incomplete data. This never happens when I run my program, but apparently it is a possibility to happen depending on the scheduling of execution between the processes? My each of my children are finding prime numbers between a range. They write these prime numbers through pipes to the parent. The parent reads these integers, but do I have to worry of the possibility that the child only gets to writing 2 of the 4 bytes for the integer before the parent starts to read?
 

Two Words

Member
I actually have something to add to my question, and another question on top of it. I made a separate program that simply executes the program I am talking about above X number of times. If any particular execution fails to work properly, the outer-most execution ends and tells me which iteration of execution failed. If I try to test 1000 executions, it works, but my laptop really kicks up a storm with the fans. I wanted to try a million sequential executions to see if the error I was talking about above may happen by chance. But I'm not sure if it is safe to do so since it will probably take hours for it to do a million executions. Does this sound unsafe to my laptop from a heat standpoint?

I just checked doing 7000 iterations, and my Macbook Pro was hitting temperatures as high as 100C on some of the cores.....
 
I actually have something to add to my question, and another question on top of it. I made a separate program that simply executes the program I am talking about above X number of times. If any particular execution fails to work properly, the outer-most execution ends and tells me which iteration of execution failed. If I try to test 1000 executions, it works, but my laptop really kicks up a storm with the fans. I wanted to try a million sequential executions to see if the error I was talking about above may happen by chance. But I'm not sure if it is safe to do so since it will probably take hours for it to do a million executions. Does this sound unsafe to my laptop from a heat standpoint?

I just checked doing 7000 iterations, and my Macbook Pro was hitting temperatures as high as 100C on some of the cores.....


100C is DEFINITELY unsafe. Don't do that. If you have to do something like this, use a desktop, or try to profile and slim down the execution cost/time. or put your (sealed) mac in ice cold water, that works too :p
 

Afrocious

Member
It's probably late as hell for this post, but here I go:

I'm a web developer who's interested in getting deeper into software development. I feel what I do is basic and boring (CRUD apps using Node or Python).

A big company is apparently interested in me. I know they're going to ask me some hardcore questions in an interview. I only know what I can recall from school 4 years ago, and I didn't even do a full CS track.

At the moment I'm reading about data structures and algorithms as a huge refresher. So I must ask: what should I be doing in order to be a better developer in order to get a better understanding of code? I know making things helps out, but I feel my current set of knowledge as a developer is limited without a great grasp on runtimes and such.
 

Aikidoka

Member
It's probably late as hell for this post, but here I go:

I'm a web developer who's interested in getting deeper into software development. I feel what I do is basic and boring (CRUD apps using Node or Python).

A big company is apparently interested in me. I know they're going to ask me some hardcore questions in an interview. I only know what I can recall from school 4 years ago, and I didn't even do a full CS track.

At the moment I'm reading about data structures and algorithms as a huge refresher. So I must ask: what should I be doing in order to be a better developer in order to get a better understanding of code? I know making things helps out, but I feel my current set of knowledge as a developer is limited without a great grasp on runtimes and such.

Caveat: I work in high-performance computing so maybe my (limited) experience is off-the-mark.

But, I think your questions may be too broad. If you have a specific company in mind, then it might be more efficient to research on the types of algorithms necessary for that specific job and also the resources they will have available.
 

JeTmAn81

Member
Thank you! This fixed my problem :) Coming from C#, I really beginn to like JavaScript's dynamic nature :)

In case you didn't realize, your example failed because you were invoking the Print line function instead of simply passing a reference which the file read procedure could invoke when it needed to. That's why err didn't exist, because the file read function needed to have the chance to create it first and then invoke the Print Line function.


It's probably late as hell for this post, but here I go:

I'm a web developer who's interested in getting deeper into software development. I feel what I do is basic and boring (CRUD apps using Node or Python).

A big company is apparently interested in me. I know they're going to ask me some hardcore questions in an interview. I only know what I can recall from school 4 years ago, and I didn't even do a full CS track.

At the moment I'm reading about data structures and algorithms as a huge refresher. So I must ask: what should I be doing in order to be a better developer in order to get a better understanding of code? I know making things helps out, but I feel my current set of knowledge as a developer is limited without a great grasp on runtimes and such.

It's probably way too late to catch up if your interview is soon. Still, I recommend these:

https://www.coursera.org/course/algs4partI

https://www.coursera.org/learn/build-a-computer

Head First Design Patterns https://www.amazon.com/dp/0596007124/?tag=neogaf0e-20
 

oxrock

Gravity is a myth, the Earth SUCKS!
Well I've gotten stuck on something again and after a ridiculous amount of time debugging and rewriting my code, I've found the culprit. A class function i created is returning 0 no matter what the actual value is. Maybe someone can give me an idea as to why?

class header file :
Code:
#pragma once
#include <vector>
#include <string>
#include <iostream>


class boxer
{
private:
	int gender;
	bool offset;
	int mHP, tournaments;
	std::string fName;
	std::string lName;
	std::vector<int> stats;
	std::vector<int> baseStats;
	bool bonus;
	int statCap;

public:
	boxer();
	boxer(boxer father, boxer mother);
	std::vector<int> getStats();
	void setStats(std::vector<int> newStats);
	std::string getName();
	std::string getLast();
	bool getOffset();
	std::vector<int> baseStatsReturn();
	int getSex();
	void roundRevive();
	void Rejuvenate();
	~boxer();

};

class file:

Code:
#include "stdafx.h"
#include "boxer.h"
#include <vector>
#include <string>

using namespace std;

boxer::boxer() {
	vector<string> femaleNames = { "Tonya","Jane","Jessica","Amy","Susan","Tammy","Erica", "Joselyn","Veronica","Laura","Betsy" };
	vector<string> maleNames = { "James","Jason","Michael","Christoper","Eric","Cameron","Ralph","Tony","John","Timothy","Craig" };
	vector<string> familyNames = { "Jones","Smith","Malloy","Potter","Miller","Doe","Simmons","Johnson","Conner","Monk","Simpson","Mars" };
	int gender =rand() % 2;
	cout << gender ;
	mHP = 100;
	tournaments = 0;
	offset = false;
	stats = { 100,10,10,10,10,10,10 };
	baseStats = stats;

	if (gender) {
		fName = maleNames[rand() % maleNames.size()];
	}
	else {
		fName = femaleNames[rand() % femaleNames.size()];
	}
	lName = familyNames[rand() % familyNames.size()];
};

boxer::boxer(boxer father, boxer mother) {
	vector<string> femaleNames = { "Tonya","Jane","Jessica","Amy","Susan","Tammy","Erica", "Joselyn","Veronica","Laura","Betsy" };
	vector<string> maleNames = { "James","Jason","Michael","Christoper","Eric","Cameron","Ralph","Tony","John","Timothy","Craig" };
	int gender = rand() % 2;
	offset = false;
	mHP = 100;
	tournaments = 0;
	bonus = false;
	int statCap = 150;
	if (gender) {
		fName = maleNames[rand() % maleNames.size()];
	}
	else {
		fName = femaleNames[rand() % femaleNames.size()];
	}
	lName = father.getLast(); //male parent
	offset = !mother.getOffset();
	stats = { 100,10,10,10,10,10,10 };
	baseStats = stats;
	
	for (int i = 1; i < stats.size() - 1; i++) {
		if ((father.getStats()[i] + mother.getStats()[i]) / 2 < statCap) {
			if (offset) {
				stats[i] = ((father.getStats()[i] + mother.getStats()[i]) / 2)+1;
				offset = !offset;
			}
			else{
			stats[i] = (father.getStats()[i] + mother.getStats()[i]) / 2;
			offset = !offset;
			}
		}
		else {
			stats[i] = statCap;
			offset = !offset;
		}
	}
	if (rand() % 5 == 3) {
		int index = rand() % 6;
		if (stats[index] < statCap - 1) {
			stats[index] += 2;
		}
		//delete index;
	}
};
void boxer::Rejuvenate() {
	stats[0] = mHP;
};

bool boxer::getOffset() {
	return offset;
};


vector<int> boxer:: getStats() {
	return stats;
};

void boxer::setStats(vector<int> newStats) {
	stats = newStats;
};
string boxer::getName() {
	return fName + " " + lName;
};

string boxer::getLast() {
	return lName;
};
int boxer::getSex() {
	return gender;
};
void boxer::roundRevive() {
	if (stats[0] + stats[5] / 4 <= mHP) {
		stats[0] += stats[5] / 4;
	}
	else {
		stats[0] = mHP;
	}
};

boxer::~boxer()
{
};
vector<int> boxer:: baseStatsReturn() {
	return baseStats;
};

The class function causing issues currently is the "getSex()" one. When the object is created, it couts the value set for "gender". But when i call object.getSex(), 0 is returned no matter what. I'm quite new to c++ so maybe I'm doing something ridiculous, but I just have no clue why it wouldn't return the proper value. I would love it if I could get an explanation as to what's happening here and how I can do it properly. Thanks guys.
 

arit

Member
Well I've gotten stuck on something again and after a ridiculous amount of time debugging and rewriting my code, I've found the culprit. A class function i created is returning 0 no matter what the actual value is. Maybe someone can give me an idea as to why?


The class function causing issues currently is the "getSex()" one. When the object is created, it couts the value set for "gender". But when i call object.getSex(), 0 is returned no matter what. I'm quite new to c++ so maybe I'm doing something ridiculous, but I just have no clue why it wouldn't return the proper value. I would love it if I could get an explanation as to what's happening here and how I can do it properly. Thanks guys.

I think rand() would be seeded with srand(1) if no call to srand() is made before, thereby you would get the same sequence of random numbers every time which just might happen to be 0 for the initializing of the gender after capping via %2.
 
Another week another nagging programming problem. Hope I'm not abusing the system hehe. This weeks assignment was pretty easy, but There is a nagging little part and I don't know if there is an easy way to fix it with my current solution.

We had to write a program that takes a user input as a String and converts each character to a lower/uppercase, ASCII value, binary and hex.


import java.util.Scanner;

Code:
public class Unit3
{
  public static void main(String[] args)
    {
		Scanner stdIn = new Scanner(System.in);

	  	String input;//user string input

	  	System.out.print("Please enter a string of any length: ");
     	input = stdIn.nextLine();

     	//Heading Print Format
     	System.out.printf("%-10s %-10s %-10s %-10s %-16s %-4s\n", "Lower", "Upper", "Initial", "ASCII", "Binary", "Hex");
     	
     	//For Loop converting String input to lowercase, uppercase, ASCII, Binary and Hex
		for(int i=0; i<input.length(); i++){
		char ch1 = input.charAt(i);
		char ch2 = Character.toLowerCase(ch1);
		char ch3 = Character.toUpperCase(ch1);
		int ascii = (int) ch1;
		String bin = Integer.toBinaryString(ch1);
		String hex = Integer.toHexString(ch1);
		
		//Print Format for conversions
		System.out.printf("%-10c %-10c %-10c %-10d %-16s %-4s\n", ch2, ch3, ch1, ascii, bin, hex);
		}

  } // end main
} // end class

a9T8fLJ.png


This output is perfect except the instructor wants the binary split in fours like this
1001 1100 also all my binaries are 7 digit, which I just realized. Any helpful hints?
 

oxrock

Gravity is a myth, the Earth SUCKS!
I think rand() would be seeded with srand(1) if no call to srand() is made before, thereby you would get the same sequence of random numbers every time which just might happen to be 0 for the initializing of the gender after capping via %2.

I didn't include my main function in interest of brevity, however "srand(time(NULL))" is actually the first line of the main function. Also, I can tell by my cout test within the boxer constructor that quite often the result of "rand() % 2 "is 1 and "gender" is set to that value. However for some reason the class function "getSex()" will always return 0 regardless.
 

Ledbetter

Member
This output is perfect except the instructor wants the binary split in fours like this
1001 1100 also all my binaries are 7 digit, which I just realized. Any helpful hints?

Check this stackoverflow question. I think for what you want, the StringBuilder solution is the most suitable one, as the binary string may vary its length (it's not always 7 digit).
 

JeTmAn81

Member
Well I've gotten stuck on something again and after a ridiculous amount of time debugging and rewriting my code, I've found the culprit. A class function i created is returning 0 no matter what the actual value is. Maybe someone can give me an idea as to why?

class header file :
Code:
#pragma once
#include <vector>
#include <string>
#include <iostream>


class boxer
{
private:
	int gender;
	bool offset;
	int mHP, tournaments;
	std::string fName;
	std::string lName;
	std::vector<int> stats;
	std::vector<int> baseStats;
	bool bonus;
	int statCap;

public:
	boxer();
	boxer(boxer father, boxer mother);
	std::vector<int> getStats();
	void setStats(std::vector<int> newStats);
	std::string getName();
	std::string getLast();
	bool getOffset();
	std::vector<int> baseStatsReturn();
	int getSex();
	void roundRevive();
	void Rejuvenate();
	~boxer();

};

class file:

Code:
#include "stdafx.h"
#include "boxer.h"
#include <vector>
#include <string>

using namespace std;

boxer::boxer() {
	vector<string> femaleNames = { "Tonya","Jane","Jessica","Amy","Susan","Tammy","Erica", "Joselyn","Veronica","Laura","Betsy" };
	vector<string> maleNames = { "James","Jason","Michael","Christoper","Eric","Cameron","Ralph","Tony","John","Timothy","Craig" };
	vector<string> familyNames = { "Jones","Smith","Malloy","Potter","Miller","Doe","Simmons","Johnson","Conner","Monk","Simpson","Mars" };
	int gender =rand() % 2;
	cout << gender ;
	mHP = 100;
	tournaments = 0;
	offset = false;
	stats = { 100,10,10,10,10,10,10 };
	baseStats = stats;

	if (gender) {
		fName = maleNames[rand() % maleNames.size()];
	}
	else {
		fName = femaleNames[rand() % femaleNames.size()];
	}
	lName = familyNames[rand() % familyNames.size()];
};

boxer::boxer(boxer father, boxer mother) {
	vector<string> femaleNames = { "Tonya","Jane","Jessica","Amy","Susan","Tammy","Erica", "Joselyn","Veronica","Laura","Betsy" };
	vector<string> maleNames = { "James","Jason","Michael","Christoper","Eric","Cameron","Ralph","Tony","John","Timothy","Craig" };
	int gender = rand() % 2;
	offset = false;
	mHP = 100;
	tournaments = 0;
	bonus = false;
	int statCap = 150;
	if (gender) {
		fName = maleNames[rand() % maleNames.size()];
	}
	else {
		fName = femaleNames[rand() % femaleNames.size()];
	}
	lName = father.getLast(); //male parent
	offset = !mother.getOffset();
	stats = { 100,10,10,10,10,10,10 };
	baseStats = stats;
	
	for (int i = 1; i < stats.size() - 1; i++) {
		if ((father.getStats()[i] + mother.getStats()[i]) / 2 < statCap) {
			if (offset) {
				stats[i] = ((father.getStats()[i] + mother.getStats()[i]) / 2)+1;
				offset = !offset;
			}
			else{
			stats[i] = (father.getStats()[i] + mother.getStats()[i]) / 2;
			offset = !offset;
			}
		}
		else {
			stats[i] = statCap;
			offset = !offset;
		}
	}
	if (rand() % 5 == 3) {
		int index = rand() % 6;
		if (stats[index] < statCap - 1) {
			stats[index] += 2;
		}
		//delete index;
	}
};
void boxer::Rejuvenate() {
	stats[0] = mHP;
};

bool boxer::getOffset() {
	return offset;
};


vector<int> boxer:: getStats() {
	return stats;
};

void boxer::setStats(vector<int> newStats) {
	stats = newStats;
};
string boxer::getName() {
	return fName + " " + lName;
};

string boxer::getLast() {
	return lName;
};
int boxer::getSex() {
	return gender;
};
void boxer::roundRevive() {
	if (stats[0] + stats[5] / 4 <= mHP) {
		stats[0] += stats[5] / 4;
	}
	else {
		stats[0] = mHP;
	}
};

boxer::~boxer()
{
};
vector<int> boxer:: baseStatsReturn() {
	return baseStats;
};

The class function causing issues currently is the "getSex()" one. When the object is created, it couts the value set for "gender". But when i call object.getSex(), 0 is returned no matter what. I'm quite new to c++ so maybe I'm doing something ridiculous, but I just have no clue why it wouldn't return the proper value. I would love it if I could get an explanation as to what's happening here and how I can do it properly. Thanks guys.

Looks to me like you're declaring a local variable gender and assigning to that rather than assigning to your object member variable named gender.
 

oxrock

Gravity is a myth, the Earth SUCKS!
Looks to me like you're declaring a local variable gender and assigning to that rather than assigning to your object member variable named gender.

Looks to me like you're right. Man I'm so bad about doing that.

Edit: removed the type declaration and code works as intended. Thanks for pointing that out. I have a bad habit of doing that.
 
Top Bottom