• 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

injurai

Banned
Obviously who better to be that guy than me, but... c++?

Wait seriously? I may be showing myself to be green. But that over even a lisp?

I feel like C++ would approach metaprogramming in a very different way. I guess instead of hinting for an explanation, I'll just ask you to sell me :p
 

Tater Tot

"My God... it's full of Starch!"
Having a lot of trouble writing my program for recursion on Java. I reread the book and I am still a bit lost and cannot get my program to compile

Write a program
where the main function calls two recursive methods. The first method will, when
given a positive whole number N, print the digits backwards.
For N=8743, output is:
3478
The second recursive method outputs a Fibonacci
sequence from 0 up to N. Given
N=57, output is:
0 1 1 2 3 5 8 13 21 34 55

Heres my code:
Code:
import java.util.Scanner;


public class lab3a {
	public static int reverseNum(int N){
		int i = 0;
		if(N <= 0){
			System.out.println("Please enter a number greater than 0");
		}
		else{
			for(i = N-1; i >= 0; i--);}
		return i;
	}
	public static int computeFibonacci(int N){
		if(N == 0 || N ==1){
		}
		
		else{
			return fib(N-1)+fib(N-2); //problem here
		}
	}

	public static void main (String[]args){
		Scanner scnr = new Scanner(System.in); //problem here
		int N = 0;	//user defined N
	    
	System.out.println("Please enter a number greater than 0:");
	N = scnr.nextInt();
	    reverseNum (N);
	    computeFibonacci(N);
	    return;
		
	
		
		
	}
}

Using the IDE eclipse. I get two errors:
Code:
1)return fib(N-1)+fib(N-2); // the method fib(int) is undefined for the type lab3a
2)Scanner scnr = new Scanner(System.in); // resource leak: 'scnr' is never closed

Im not sure how to solve these problems. Also could someone take a look at my code and find ways for me to improve it please. Thanks.
 
I feel like the value of having a nice display is often over looked. Our job is to write and read text on computer screens for hours at a time.
I know when I upgraded to even just a 1080p display the difference was huge when writing code. Hopefully my next laptop will have 2560x1440....

I got both an 13 Air and 15 Pro. I'd take the lighter computer any day over the nicer screen. Retina is nice but overrated.
 
Wait seriously? I may be showing myself to be green. But that over even a lisp?

I feel like C++ would approach metaprogramming in a very different way. I guess instead of hinting for an explanation, I'll just ask you to sell me :p

To be completely honest, I don't know much about metaprogramming in any language other than C++. So I can't really make a fair comparison. As my username suggests, I'm biased, so I just suggested in because that's what I do :)

I suspect that compared to a lot of programming languages C++ metaprogramming (template metaprogramming, specifically) is really obtuse, and verbose. But C++ was never really designed with metaprogramming in mind, it's just something that evolved over the course of many years and turned out to be really interesting.

The unique thing about C++ template metaprogramming is that you're not writing a program that transforms other programs at runtime, you're writing a program that transforms itself at compile time. Template metaprogramming is 100% a compile time thing.

Apparently it has a whole page on Wikipedia, where you can read more, with some examples: http://en.wikipedia.org/wiki/Template_metaprogramming
 

NotBacon

Member
Having a lot of trouble writing my program for recursion on Java. I reread the book and I am still a bit lost and cannot get my program to compile

Heres my code:
Code:
import java.util.Scanner;


public class lab3a {
	public static int reverseNum(int N){
		int i = 0;
		if(N <= 0){
			System.out.println("Please enter a number greater than 0");
		}
		else{
			for(i = N-1; i >= 0; i--);}
		return i;
	}
	public static int computeFibonacci(int N){
		if(N == 0 || N ==1){
		}
		
		else{
			return fib(N-1)+fib(N-2); //problem here
		}
	}

	public static void main (String[]args){
		Scanner scnr = new Scanner(System.in); //problem here
		int N = 0;	//user defined N
	    
	System.out.println("Please enter a number greater than 0:");
	N = scnr.nextInt();
	    reverseNum (N);
	    computeFibonacci(N);
	    return;
		
	
		
		
	}
}

Using the IDE eclipse. I get two errors:
Code:
1)return fib(N-1)+fib(N-2); // the method fib(int) is undefined for the type lab3a
2)Scanner scnr = new Scanner(System.in); // resource leak: 'scnr' is never closed

Im not sure how to solve these problems. Also could someone take a look at my code and find ways for me to improve it please. Thanks.

Well the error isn't lying to you :p

You don't have a method called fib() defined anywhere, so you can't call fib(N-1) or fib(N-2). You're going to want to call computeFibonacci() because that is defined. Also you don't have a base case, if (N==0 || N==1) should return something. Trace out on paper, step by step, what exactly would return from the method if (for example) computeFibonacci(5) was called.

As for the Scanner, it's telling you that it needs to be closed when you're done with it. So look at the documentation for Scanner and see if it has a close() method.

Also your reverseNum(int N) method probably doesn't work. It's either just going to print (which will cause an error because the method needs to return something) or return 0.
 
Thanks. We went with the airbnb standard. What was it that you didn't like about Crockfords?

Oh yeah, it wasn't that much about the code conventions themselves but how JSLint enforces them: for example there might be a piece of code (like 3 back-to-back-functions which call each other) which can't be refactored so that one of them wouldn't throw a latedef warning. But JSLint doesn't offer an option to ignore one line or block, so you have to either deal with the warnings or just turn the latedef-warning to false all together which in most cases isn't a good idea. And so on.
 

Protome

Member
Well the error isn't lying to you :p

You don't have a method called fib() defined anywhere, so you can't call fib(N-1) or fib(N-2). You're going to want to call computeFibonacci() because that is defined. Also you don't have a base case, if (N==0 || N==1) should return something. Trace out on paper, step by step, what exactly would return from the method if (for example) computeFibonacci(5) was called.

As for the Scanner, it's telling you that it needs to be closed when you're done with it. So look at the documentation for Scanner and see if it has a close() method.

Also your reverseNum(int N) method probably doesn't work. It's either just going to print (which will cause an error because the method needs to return something) or return 0.

I'd also add as a small point that if (N <= 1) is neater than N==0 || N==1.
 
I'd also add as a small point that if (N <= 1) is neater than N==0 || N==1.

I'll reverse point out that 0 and 1 are correct inputs for the function. The full range of integers <= 1 are not.

Tater Tot, in addition to your other necessary fixes, add a validation to prevent negative numbers. If I'm your professor/TA/whatever, I'll test it with -1 and deduct points for the stack overflow error.
 

danthefan

Member
Hi guys, just wondering if there are any other sites like Project Euler out there? I'm really enjoying that site but my progess has really slowed as the problems get harder.
 

mvtn

Member
I have bound Escape key to Caps Lock and it really helped me to fasten my Vim workflow.

Speaking of Vim, anybody here feels like sharing his .vimrc? Internet is full of dotfiles already, but why not.
 
I have bound Escape key to Caps Lock and it really helped me to fasten my Vim workflow.

Speaking of Vim, anybody here feels like sharing his .vimrc? Internet is full of dotfiles already, but why not.

My .vimrc is pretty bare, but I map <esc> to the letters jk. This way I don't have to even shift my hand down, I can stay in home row, then I map capslock to ctrl (at the OS level) which I find easier to hit than the actual ctrl key.
 

Nesotenso

Member
Speaking of vim, I was hoping to learn how to make most of it by using Derek Wyatt's tutorials. Are those pretty effective and useful? I do have a copy of the book of the Practical Vim but I don't have the time to read it.
 

mvtn

Member
Speaking of vim, I was hoping to learn how to make most of it by using Derek Wyatt's tutorials. Are those pretty effective and useful? I do have a copy of the book of the Practical Vim but I don't have the time to read it.

Yep, I've watched most of his video tutorials and they're pretty helpful.
 

Quixzlizx

Member
Can anyone tell me the differences between Visual Studio 2013 Express and Visual Studio 2013 Community? I've recently bought Head First C#, which uses Visual Studio 2013. I'm not interested in Windows Store apps, but this book has an addendum to replace the Store projects with desktop projects.

Or would I be better off just learning on VS 2015 RC, despite all of the books out there being for 2013? There only seems to be a Community version of that one, though.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
In the old Express line, there would be one separate Express IDE for every language.

That might be the difference. Where you get the whole shebang in Community, Express lets you pick and choose what languages you want to have installed.
 
Can anyone tell me the differences between Visual Studio 2013 Express and Visual Studio 2013 Community? I've recently bought Head First C#, which uses Visual Studio 2013. I'm not interested in Windows Store apps, but this book has an addendum to replace the Store projects with desktop projects.

Or would I be better off just learning on VS 2015 RC, despite all of the books out there being for 2013? There only seems to be a Community version of that one, though.

As Haly mentioned, go with Community over the Express options. It's the full featured Visual Studio experience, licensed for free usage by individuals and small businesses up to various revenue/personnel/equipment thresholds. You could probably get by using 2015, just know there could be some places where the tools and/or languages have changed and the books might show you things that your environment won't replicate. On that point, it might be easier to use 2013 while using those resources, and then upgrade to 2015 afterwards (a Community version should also be available once 2015 goes to retail).
 

injurai

Banned
Watching the Swift WWDC talk right now, loving all these additions. Once the thing goes open source it could be real competitor to Rust, imho.

Ehh... that certainly remains to be seen either way. Swift is not going to really make a splash as a systems language at all. It will be targeting client application programming. So both OSX Applications and iOS Apps.

I will agree that Rust and Swift both push each other. Both teams have limited resources and they can learn from each others attempts to unify various language semantics and constructs.

Just as Go is not really rubbing shoulders with Rust's domain anymore, I feel the same will be true for Swift. It will be Apple's equivalent to what Microsoft has made C# for programming within their Windows environment. While at the same time C# is open source and enjoys wide usage outside of windows. With the benefit that Microsoft has invested so heavily in the C# ecosystem and development toolings.

Rust is more competing with the domain of C++/D by tackling pitfalls of non-GC memory management. Something swift still is not doing. Of course there is overlap, but anymore languages are designed for various task and needs.
 

Quixzlizx

Member
In the old Express line, there would be one separate Express IDE for every language.

That might be the difference. Where you get the whole shebang in Community, Express lets you pick and choose what languages you want to have installed.

As Haly mentioned, go with Community over the Express options. It's the full featured Visual Studio experience, licensed for free usage by individuals and small businesses up to various revenue/personnel/equipment thresholds. You could probably get by using 2015, just know there could be some places where the tools and/or languages have changed and the books might show you things that your environment won't replicate. On that point, it might be easier to use 2013 while using those resources, and then upgrade to 2015 afterwards (a Community version should also be available once 2015 goes to retail).

Thank you for the explanations. I will start off with 2013 Community, then.
 

Anduril

Member
Don't know if it was just overlooked or nobody actually had anything to contribute, but I'm gonna try this again:

Hey guys,

I'm more or less a programming noob, having tried to get into Java and Android programming through various books and online courses and gave up twice in the last two years. Now I'm working my way through the bitfountain course (about half way through) and I started a side project to start coding by myself. Lacking the experience and a whole lot of knowledge, I come to you for advice.

So, I'm making a dice throwing app and one of the activities is gonna be a custom dice throw, where you can add/remove custom sided dice from the collection and then throw all of them at once (maybe later individually too).

As of now, I've created a die object, succesfully implemented the buttons that add/remove a die (well, only the last die for now) from an arraylist, but the whole thing is done by programatically adding/removing textviews (for testing, later imageviews) in the most crude way possible with a few elseif and for statements. This brings me all sort of problems with styling the textviews and just seems redundant.

Is there a way to make an object have its own UI object and remove one with the other? Or at least a smarter way of going about this that I'm not thinking of?

Thanks for any suggestions!
Yay selfquoting!
 

Big Chungus

Member
Is it worth applying for a programming job if you barely meet their requirements?

I know the company has hired students from the same program I graduated from (2 year business programming/it) but it's been a year and my programming skills are a bit rusty.
 

injurai

Banned
A lisp like Racket or Clojure. Or Elixir, which runs on the Erlang VM.

I was really considering learning Elixir a few months back. I think I dropped it because I deemed Erlang a bit too esoteric for the investment. But I guess I presumed that since you can call into Erlang from Elixir that I'd be also limited to what Erlang brought to the table. I do assume Elixir is still garbage collected the same way.

But maybe I'll take another dive. Lisp, racket and clojure are other options. I know a few people who really swear by clojure as a productive and powerful language. I rag on java, but the jvm environment without a doubt is a luxury.
 
Is it worth applying for a programming job if you barely meet their requirements?

I know the company has hired students from the same program I graduated from (2 year business programming/it) but it's been a year and my programming skills are a bit rusty.

I would turn this around a bit and say It's never worth applying for a job unless you barely meet the requirements. If you're an expert at everything they're doing, what are you going to learn on the job?
 
Is it worth applying for a programming job if you barely meet their requirements?

I know the company has hired students from the same program I graduated from (2 year business programming/it) but it's been a year and my programming skills are a bit rusty.

Worst case scenario you don't get an interview or you get an interview and your skills get exposed pretty quickly. If your skills or lack thereof are exposed and the company doesn't feel they can afford to train you up, then well you're back to square one but all you've lost is your time.

My suggestion is check out some books on programming interviews and see how much, if any, of the topics you know.

I mostly deal with OO languages and non web technologies (and a lot of game dev) so for me the topics I've encountered most in interviews are:

General OO concepts (polymorphism, encapsulation)
How to use virtual functions to accomplish the above
Algorithms (I hate run time complexity questions and I always do bad on them), search and sort are things that come up a lot.
Bitwise operations
Hexadecimal
Data structures (advantages/disadvantages, when and why to use)
the STL
Vector Math (this is strictly a game dev stuff)
Networking concepts (tcp/udp and client server) but this is usually gamedev related.

And usually some white board problem (common ones: reverse a string in place, write a linked list and an insert function, sort an array, shuffle a deck of cards).

Now I've never interviewed for anything webdev, or database or server side engineering related so those jobs likely have far different requirements, but the more generic computer science stuff is always good (algorithms, data structures, big o).
 

Qurupeke

Member
Is this book good for C++? I did the mistake to take a book about C++ algorithms and not the language itself at my programming class but I really need to find something to read other than online free tutorials. I already know quite a few after 3 months and I've already coded my first big program but I still want to see some stuff like polymorphism, inheritence or certain containers like AVL trees more in depth.
 

leroidys

Member
Is it worth applying for a programming job if you barely meet their requirements?

I know the company has hired students from the same program I graduated from (2 year business programming/it) but it's been a year and my programming skills are a bit rusty.

More often than not, job postings are wishlists posted by the employer. I would definitely apply unless the requirement is a doctorate with a specific focus or something.
 

vypek

Member
Is this book good for C++? I did the mistake to take a book about C++ algorithms and not the language itself at my programming class but I really need to find something to read other than online free tutorials. I already know quite a few after 3 months and I've already coded my first big program but I still want to see some stuff like polymorphism, inheritence or certain containers like AVL trees more in depth.

I'm certainly far from an expert and don't own the book but just thought I'd say that the book you linked to as well as "Accelerated C++" by Koenig are two of the most recommended books I see. I'm thinking about diving back into C++ pretty hard and continuing where I left off so maybe I'll pick these books up.

Is it worth applying for a programming job if you barely meet their requirements?

I know the company has hired students from the same program I graduated from (2 year business programming/it) but it's been a year and my programming skills are a bit rusty.

As someone who is in a somewhat similar situation, I would say go for it. I've gotten a few interviews from places where I applied and barely met the requirements. And sometimes calls from places where I was under the requirements they had.
 
Barely meeting the requirements is meeting the requirements.

There is that. At least do that. Hit all the major bullet points, at least.

As someone who has occasionally been dragged into phone screens and interviews, nothing annoys me more than someone who clearly does not have the experience we asked for, or even the experience he or she lists on his or her own résumé. Don't waste my time.
 
Having a lot of trouble writing my program for recursion on Java. I reread the book and I am still a bit lost and cannot get my program to compile



Heres my code:
Code:
import java.util.Scanner;


public class lab3a {
	public static int reverseNum(int N){
		int i = 0;
		if(N <= 0){
			System.out.println("Please enter a number greater than 0");
		}
		else{
			for(i = N-1; i >= 0; i--);}
		return i;
	}
	public static int computeFibonacci(int N){
		if(N == 0 || N ==1){
		}
		
		else{
			return fib(N-1)+fib(N-2); //problem here
		}
	}

	public static void main (String[]args){
		Scanner scnr = new Scanner(System.in); //problem here
		int N = 0;	//user defined N
	    
	System.out.println("Please enter a number greater than 0:");
	N = scnr.nextInt();
	    reverseNum (N);
	    computeFibonacci(N);
	    return;
		
	
		
		
	}
}

Using the IDE eclipse. I get two errors:
Code:
1)return fib(N-1)+fib(N-2); // the method fib(int) is undefined for the type lab3a
2)Scanner scnr = new Scanner(System.in); // resource leak: 'scnr' is never closed

Im not sure how to solve these problems. Also could someone take a look at my code and find ways for me to improve it please. Thanks.

I don't mean to pick on you, but none of these methods really do anything and there are a lot of basic conceptual issues. I think the most helpful thing you can do is start with just a single method- say reverseNum() - and try to get it to work, don't even need the user input or anything, just:

Code:
public class Whatever {
  public static int reverseNum(int N) {
       //try stuff here that reverses a number
  }

  public static void main(String[] args) {
    
      System.out.println(Whatever.reverseNum(157));
  }
}

I think that will let you figure it out more than anything else. Your current reverseNum method isn't doing what you would want it to.

Then just take this approach to the next step of the problem.
 
I'm confused. Why don't you just add the extra condition to the where clause?

The first join guarantees that employee.ssn == dependent.essn.
The second join guarantees employee.superssn = employee.ssn.

You don't need a join for the second part.

Code:
select e.lname,e.fname
from employee e join 
dependent d on e.ssn = d.essn 
 where d.dependent_name = 'joy'
 and e.ssn = e.superssn

This isn't the same as the original query:
Code:
select em.lname,em.fname
from employee e join 
dependent d on e.ssn = d.essn join
 employee em on em.superssn =e.ssn
 where d.dependent_name = 'joy'

Maybe that's a good thing, since he doesn't seem to like the results from the first query. But the two aren't logically equivalent. The first one can traverse rows with the comparison (it can join rows from employee to other rows from employee), the second one only filters to rows where the two values are equal. It just depends on what he wants with the query.

I'm not sure I've ever seen a join from a table back to the same table.

Self-joins are often extremely useful :)

Yep that's about it. I'm comparing data from dependent table essn to the employee table ssn. Then I use the results I got and take its superssn and compare it to the employee table again and find the another match. I tried the left outer join but It gave me the same results.

From your description, it sounds like what you're looking for is this:
Code:
select em.lname,em.fname
from employee e join 
dependent d on e.ssn = d.essn join
 employee em on[B] em.ssn =e.superssn[/B]
 where d.dependent_name = 'joy'

(the original query, but with the fields reversed in this join).
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Thought this was entertaining.

M1Uctmn.png

https://twitter.com/mxcl/status/608682016205344768
 

Water

Member
I'm certainly far from an expert and don't own the book but just thought I'd say that the book you linked to as well as "Accelerated C++" by Koenig are two of the most recommended books I see. I'm thinking about diving back into C++ pretty hard and continuing where I left off so maybe I'll pick these books up.
While "Accelerated" is excellent quality, it's also in a weird place where it's perhaps a bit too thin for people with a lot of experience in other languages and too deep for beginners to programming. And it's 15 years old, so it's (sort of) outdated. Someone really should write a new version of it for modern C++. That said, if you start from "Accelerated" and essentially learn the C++98 way of writing things first, it is an easy step to graduate to modern C++ because it's just adding (a lot of) features to do the same things better. But starting directly from modern C++ is much less painful since you won't have to learn many weird workarounds that were necessary in C++98.

I'd recommend Stroustrup's "C++ Programming Language 4th ed." over the Primer. Not that the Primer is bad - it's actually pretty good I think - but it's not very good at anything either.

The initial sections of TCPL are collected in the smaller book "A Tour of C++", and most of that is available completely free as PDFs from isocpp.org, so there's no reason not to read at least that much.
 
So I've been doing codecademy and I'm doing the extra credit for the Battleship section.

I'm trying to implement multiple ships. I'm not quite sure if I'm going about this the best way. I've decided not to use classes for this, though I'm growing increasingly convinced that would be the better option here. But meh.

Code:
from random import randint

def gen_board():
	board = []
	for x in range(5):
		board.append(['0'] * 5)
	return board 

[B]Board is going to be essentially going to be a 5x5 grid, with spaces on the board being represented by '0' at the start.[/B]
	
def play_game():
	board = gen_board() 
	gen_small(board)
	display_board(board)

[B]Incomplete, but this will run the whole game.[/B]
	
def is_occupied(board, row, col):
	if board[row][col] == '0':
		print "This space is unoccupied"
		return True 
	else:
		print "There is a ship here already" 
		return False 

[B]Thinking of using this function to test whether a board space is already taken. This will potentially be of use when I add multiple ships to the board. See gen_small(board) function to see how I'm currently going about generating the ships.[/B]
		
def rand_row(board):
	ship_row = randint(0, len(board) - 1)
	return ship_row
	
def rand_col(board): 
	ship_col = randint(0, len(board) - 1)
	return ship_col
	
def gen_small(board):
	vert_hor = randint(0,1)
	gsrow = rand_row(board)
	gscol = rand_col(board) 
	board[gsrow][gscol] = '1'

[B]Right now the ship is simply one space on the 5x5 grid. I'm thinking of making the ships different sizes. What I'd do is first use vert_hor to randomly determine if the ship is going to be horizontal or vertical. If horizontal, I'll add or subtract 1 from gsrow to make the second space. I'll just need to make sure that space is both on the board, and unoccupied by another ship. If vertical I do the same, but add or substract 1 from gscol.[/B]

[B]Right now what happens is I have my board which looks like

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

the way I'm doing things now I place ships on the board by simply converting one of those 0's to at string. '1' for the small ship. Perhaps '2' for a bigger ship. So if small ship is determined to be column 0, row 1 we'd get:

0 0 0 0 0
1 0 0 0 0
0 0 0 0 0
0 0 0 0 0 [/B]

[B]This has some issues because I'll need to display a board that does not show this information to the player. My current display_board function doesn't work for that so it will need remaking. But I'm also worried that this is just a bad way of generating ships. For one, every new ship I generate means I have to find some convoluted way of getting randrow and randcol to not generate an already selected row/col combination. I guess I could use the is_occupied() function. It also is going to be difficult to make the ships bigger I believe. There has to be some better way to do this.[/B]
	
def display_board(board):
	for row in board:
		print ' '.join(row) 

[B]This needs reworking so that it simply displays '0' and 'X' for unguessed spaces and guessed spaces respectively. Perhaps only showing the integer on a successful hit. Not quite sure how to do that. Right now it would display ship locations to the player which is ok for testing, but awful for later on.[/B]
		
play_game()
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Seems fine to me. You just need to add a third number, 2 to show hits, and then convert 2s to Xs and 0s and 1s to ?s when you're displaying it.
 
Seems fine to me. You just need to add a third number, 2 to show hits, and then convert 2s to Xs and 0s and 1s to ?s when you're displaying it.

Huh so its not an overly convoluted way of going about ship generation?

And yeah that solution works. I could make all the unknown spaces ? marks. Make bad guesses X. And make hits some other symbol. Preferably I'd like the player to know which ship they hit though, which requires a special character for each ship. Which means I have to store that information somewhere that isn't just in the gen_small(board) function. Right? I somehow have to send the ship location information to my display board function.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
I can't think of any convenient way of getting randomized configurations of ships onto the board so the generation code is going to look like a mess anyway. What you're basically going to do is choose a starting point (check if it's empty), choose a direction (right or down), and then start filling in those spaces with the ship. If there's a conflict, scrap it (reset all those slots to 0) and try again.

You just need to give every ship a unique number and then store that in the board. By revealing that number, you inform the player which class of ship they hit, though you'll want to make this information available elsewhere.

As for what a ship "is", if you don't want to give it a class, you can simply treat them as tuples (pairs of 2). The first number indicates its "name", and the second indicates the number of spaces it occupies. Then you throw them all into an array and you loop over it, trying to fit every ship onto the board somehow.

Since you're printing to the console, I suggest outputting 2 digits so it lines up nice and even using a monospace font.
 

vypek

Member
While "Accelerated" is excellent quality, it's also in a weird place where it's perhaps a bit too thin for people with a lot of experience in other languages and too deep for beginners to programming. And it's 15 years old, so it's (sort of) outdated. Someone really should write a new version of it for modern C++. That said, if you start from "Accelerated" and essentially learn the C++98 way of writing things first, it is an easy step to graduate to modern C++ because it's just adding (a lot of) features to do the same things better. But starting directly from modern C++ is much less painful since you won't have to learn many weird workarounds that were necessary in C++98.

I'd recommend Stroustrup's "C++ Programming Language 4th ed." over the Primer. Not that the Primer is bad - it's actually pretty good I think - but it's not very good at anything either.

The initial sections of TCPL are collected in the smaller book "A Tour of C++", and most of that is available completely free as PDFs from isocpp.org, so there's no reason not to read at least that much.

Okay, I see what you're saying. By the way you describe it, it seems like Accelerated C++ might not be the perfect book for me.

I'll check out Stroustrup's book though as well as take a look at isocpp.org. Thanks for the information and clarification.
 

Qurupeke

Member
I'm certainly far from an expert and don't own the book but just thought I'd say that the book you linked to as well as "Accelerated C++" by Koenig are two of the most recommended books I see. I'm thinking about diving back into C++ pretty hard and continuing where I left off so maybe I'll pick these books up.

Nice to know.
 
I can't think of any convenient way of getting randomized configurations of ships onto the board so the generation code is going to look like a mess anyway. What you're basically going to do is choose a starting point (check if it's empty), choose a direction (right or down), and then start filling in those spaces with the ship. If there's a conflict, scrap it (reset all those slots to 0) and try again.

You just need to give every ship a unique number and then store that in the board. By revealing that number, you inform the player which class of ship they hit, though you'll want to make this information available elsewhere.

As for what a ship "is", if you don't want to give it a class, you can simply treat them as tuples (pairs of 2). The first number indicates its "name", and the second indicates the number of spaces it occupies. Then you throw them all into an array and you loop over it, trying to fit every ship onto the board somehow.

Since you're printing to the console, I suggest outputting 2 digits so it lines up nice and even using a monospace font.

I think I found a way that I'm reasonably satisfied with.

Code:
def gen_small(board):
	vert_hor = 0 
	gsrow = rand_row(board)
	gscol = rand_col(board) 
	#print "gsrow:", gsrow
	#print "gscol:", gscol 
	board[gsrow][gscol] = '1'
	if vert_hor == 0 and (gscol + 1) <= 4:
		board[gsrow][gscol + 1] = '1' 
	elif vert_hor == 0 and (gscol - 1) >= 0:
		board[gsrow][gscol - 1] = '1'

Unfinished but it works as intended thus far. I'll just have to make vert_hor = randint(0,1) and then write the cases for when it equals 1.

Meanwhile I display the board with:

Code:
def display_board(board):
	for row in board:
		board = ' '.join(row) 
		board = board.replace('0', '?')
		board = board.replace('1', '?') 
		print board

And then the game is run via:

Code:
def play_game():
	board = gen_board() 
	gen_small(board)
	guesses = 0
	hits = 0
	print "Can you find the battleship?" 
	while guesses < 4:
		display_board(board)
		row = int(raw_input("Guess row: "))
		col = int(raw_input("Guess column: "))
		if board[row][col] != 'X' and board[row][col] != '0':
			print "HIT" 
			guesses += 1 
			hits += 1 
			if board[row][col] == '1':
				board[row][col] = 's'
		else: 
			print "wrong" 
			board[row][col] = 'x' 
			guesses += 1 
		if hits == 2:
			print "You won!"
			break 
		print "You lost"

The run game code is also incomplete since I haven't added cases for when they go off the map, or if they choose a number they already chose. I also couldn't figure out a better way of checking for a win, but this works. I know that right now I only have 1 ship of size 2. Meaning the player has to get 2 hits to win. So I just need a hit counter.

I really do think this is something better done with classes, especially if I had a desire to make it multiplayer or add in an opponent AI. But I'm fine with it for now. I actually probably could make it multiplayer with a few tweaks. But I'll work on adding more ships before doing anything like that.

What confuses me most is the display board function. Stuff like gen_small(board) seem to mutate the board when I do things like board[gsrow][gscol] = '1'. But the display board function doesn't mutate it when I do things like board = ' '.join(row), board = board.replace('0', '?'), board = board.replace('1', '?'). Which is fine because I want things to behave like that. I'm just not too clear why.

A board will display as:

? ? ? ? ?
? ? ? ? ?
? ? ? ? ?
? ? ? ? ?

But underneath the hood it is:

? 1 1 ? ?
? ? ? ? ?
? ? ? ? ?
? ? ? ? ?

Which I know because if I enter the proper coordinates it will register as a hit and then display as

? s s ? ?
? ? ? ? ?
? ? ? ? ?
? ? ? ? ?

And that means the program somehow knows that those two ? marks are really 1s underneath the hood, otherwise it wouldn't update them to 's' upon a successful hit.
 
Dear ProgrammingGAF,

I've been feeling more and more restless with my current job. I've been looking for new ones, and I've been getting this urge to get back into coding. I would like to do it for a career, but I have no professional or even personal experience outside of academics. I have an Associate of Science degree in Computer Science which I got last summer, but I didn't actually write any code, just transferred credits and fulfilled requirements for the program. Many, many years ago I wrote programs in Pascal, C++, and Java.

I'm looking for a path to writing code as a job. I'm looking for the quickest path possible and I'm willing to do whatever it takes. There was a time where I was intimidated by my peers (and professors) in Computer Science courses because they lived and breathed the stuff. But I've since found in my professional endeavors that living and breathing stuff is what produces the most success. I sure as hell don't want to live and breath UPS anymore. I don't believe in destiny, but there's a desire inside me that's compelling me to try and be a programmer.

So many of the job opportunities I see are looking for so much professional experience. Does that mean I should be looking at internships to get my foot in the door?

What about developing my skills on my own time? Is there a good online resource to start again and grow? I've heard mention of free online courses, but I don't know what's good for what and I just feel lost and desperate.

Anyways, thanks in advance for any advice you can provide.

Warm Regards,

Richard Welsh, a.k.a. HiredN00bs
 
Top Bottom