• 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

CrankyJay

Banned
I've been using C++/C for two years. I started learning Python this past week and decided to solve the same problem in three different languages (like reversing strings) to test my knowledge.

reversing string program in C++: 2hrs
reversing string program in C: 2.5hrs
reversing string program in Python: 15mins

I'm not so sure the C's are for me lol.

Because Python has a convenience function for this? Come on son.
 

TheExodu5

Banned
Anyone use Swift? Looking to start some iOS development, so I'm going to start learning it. Seems pretty intuitive, coming from Java development.
 
I've been messing around wiith the new Java Nashorn Javascript engine and I can't figure out how to call a method on a Java object in Javascript code. I've been looking around but I can't really find anything. Here's what I want to do: I have a global variable that is set by an init function. The init function sets the global variable to an object that is passed from Java code. Then I want to call a method from that global object. This is where my code fails, I get the following error:
Code:
javax.script.ScriptException: TypeError: Foo{a='hello', b=1245} has no such function "getA" in <eval> at line number 1

https://gist.github.com/GyrosOfWar/e41f7b5adab0b186dddd
Here's a bit of code that illustrates this problem.

edit: Oh man, I fixed it. The mistake was that the Foo class (in this case) has to be public, not just package-visible so it can be called from JS.
 
Because Python has a convenience function for this? Come on son.
Hey, I'm far from good. As Der Flatulator showed, it's not so hard in C++ either.

EDIT: Not that I'm fine being where I'm at, mind you. It's aggravating so I've taken the initiative to really dig in and get better at a much quicker pace than I have before.
 

nan0

Member
I've been using C++/C for two years. I started learning Python this past week and decided to solve the same problem in three different languages (like reversing strings) to test my knowledge.

reversing string program in C++: 2hrs
reversing string program in C: 2.5hrs
reversing string program in Python: 15mins

I'm not so sure the C's are for me lol.


You should try C#:

Code:
using System.IO;
using System;

class Program
{
    static void Main()
    {      
       Console.WriteLine("SomeString".Reverse());
    }    
}

//As reusable Extension method
public static class ExtensionMethods{

  public static string Reverse(this string s )
  {
    char[] reversalArray = s.ToCharArray();
    Array.Reverse(reversalArray);
    return new string(reversalArray);
  } 

}

You could just dump Reverse(string) in a regular method, but that's what Extension methods are for.
 

Kalnos

Banned
Anyone use Swift? Looking to start some iOS development, so I'm going to start learning it. Seems pretty intuitive, coming from Java development.

I'm using it for work right now, it has been smooth so far outside of some bugginess with the XCode Beta.
 
You should try C#:

Code:
using System.IO;
using System;

class Program
{
    static void Main()
    {      
       Console.WriteLine("SomeString".Reverse());
    }    
}

//As reusable Extension method
public static class ExtensionMethods{

  public static string Reverse(this string s )
  {
    char[] reversalArray = s.ToCharArray();
    Array.Reverse(reversalArray);
    return new string(reversalArray);
  } 

}

You could just dump Reverse(string) in a regular method, but that's what Extension methods are for.

Real talk, I want to learn C#. For some reason, I find Microsoft's materials unhelpful in actually learning the language though. I'm probably not looking at the right stuff, so if you or anybody can point me in a good direction that would be a tremendous help.
 

nan0

Member
Real talk, I want to learn C#. For some reason, I find Microsoft's materials unhelpful in actually learning the language though. I'm probably not looking at the right stuff, so if you or anybody can point me in a good direction that would be a tremendous help.
I'm a big fan of C# in a Nutshell. If you're not into step-by-step tutorials and already have experience in other languages, it's a very good choice for both the basics as well as advanced stuff like delegates, LINQ, threading, serialization etc. It's rather expensive though, $50 I think. Google books has a preview version IIRC, but it's from one of the first editions which doesn't cover C# 4 and 5.
 
Anyone use Swift? Looking to start some iOS development, so I'm going to start learning it. Seems pretty intuitive, coming from Java development.

It is okay. Its easy enough to pick up as someone who already knows Obj-C because it uses a reduced version of the same API. I don't really like that it defaults floating precision to double but I get it. It still feels incredibly immature though. I wonder if it really will be ready on release.
 

msv

Member
Any good resources detailing proper and more complex usage of expression trees in c#? Performance comparisons would be nice as well. I've used them a bit, but I'd love to read up about it in more detail.
 

Water

Member
C++:

Code:
#include <algorithm>
#include <iostream>
int main() {
  string str = "some string";
  std::reverse(str.start(), str.end());
  std::cout >> str >> endl;
  return 0;
}
You don't even have to know that there's a ready-made implementation of reverse in <algorithm> if you do:
Code:
string str = "some string";
auto reversed = string(str.crbegin(), str.crend());
 
So I recently found this awesome tutorial on building a toy browser engine in Rust (systems programming language developed by Mozilla). I've spent the last two evenings re-implementing the thing in Java 8 and I have to say, Java 8 is so much nicer to use than Java 7. There's still a couple of warts (why can I only have one public class/interface/whatever per file?) but it's kinda fun to use now.

As for the engine, it only parses a small subset of HTML and CSS, but it's still pretty cool. I've managed to hook up the Nashorn JS engine to execute scripts that are contained in the HTML file or linked in the HTML file and it now also has a DOM object that at some point will make it possible to manipulate the DOM from Javascript. Still have to figure out how to feed the manipulated DOM from the JS back to the browser engine.

Here's the source.
 

Slavik81

Member
Why do all C/C++ build systems suck? Make is arcane, but I think I might end up going back to it.

Nobody uses boost jam. QMAKE is full of magic. waf is almost ideal but too complicated to extend. Tup is Linux-only.

I have half a mind to write my own build system. Or, maybe I should learn cmake.
Has anyone tried Shake? I have to admit, I like the idea of learning a Haskell-based build system.
 

oxrock

Gravity is a myth, the Earth SUCKS!
I've been using C++/C for two years. I started learning Python this past week and decided to solve the same problem in three different languages (like reversing strings) to test my knowledge.

reversing string program in C++: 2hrs
reversing string program in C: 2.5hrs
reversing string program in Python: 15mins

I'm not so sure the C's are for me lol.

From my experience, python is one of the easiest languages to understand for beginners and hit the ground running right out of the gate. Most other languages take more time to understand exactly how things work first. So regardless of python's built in ability to read strings backwards, the time investment you posted makes perfect sense for a beginner to me.

That doesn't mean forsake the C languages! It just means it'll likely take more time until you're as comfortable writing in them. It'll come through time and experience and before long you can look down upon all us "noob" scripting language programmers. :p
 

NotBacon

Member
I'm thinking about writing a compiler in C or Python....
The source language would be something simple I made up (or a subset of an existing language?), and the target is going to be LLVM I think.

Suggestions?
 

oxrock

Gravity is a myth, the Earth SUCKS!
I'm thinking about writing a compiler in C or Python....
The source language would be something simple I made up (or a subset of an existing language?), and the target is going to be LLVM I think.

Suggestions?

This got me wondering, as someone who primarily codes in python I often looks for ways to speed things up a bit. Does using iron python or jython lead to faster runtimes than IDLE with identical programs? If so, would it be considerable?
 

phoenixyz

Member
This got me wondering, as someone who primarily codes in python I often looks for ways to speed things up a bit. Does using iron python or jython lead to faster runtimes than IDLE with identical programs? If so, would it be considerable?

In most cases using Pypy results in some serious speedup. If you need more then you could look into CFFI and Cython.
 

Lathentar

Looking for Pants
Spent this weekend writing a PopWords solver in python. PopWords is a game on the AppStore with a daily challenge.

Rules:
8x8 grid of letters
Make words by chaining letters together (start at a letter and continue to any unused letters left/right/up/down/diagonal).
Words of length 3 or higher. Points per word length are as follows: 1, 2, 4, 7, 11, 17, 25, 35?, 50, 70?, 100?, 140, 200, 270, unknown higher....
When a word is made, letters fall down to fill empty spots, then empty columns are removed.
Removing all letters doubles the user's score.

Current situation:
I've been able to write a solver (see: https://github.com/Lathentar/PopWordSolver), but it is far too slow for the 8x8 grid. So far it's taken well over 5 hours for the daily puzzle.

Approach:
Take the word bank and make a n-tree where n is the number of letters available at each step of the tree. When finding words, find the letter, see if the letter is available in the given spot of the tree. Then use the tree at that letter for the next letter. Search for a '*' in the tree to see if you've made a completed word as well.

I use a depth first traversal after discovering all words that can be found on the current board sorted by length. For every board I encounter, I generate a string and put it into a dictionary with the result of that depth first search. Before traversing the board, I check to see if I've already seen that board and already know what the best solution is (memoization). I also check to see if it's possible to beat the best current score given the number of letters remaining on the board.

What other approaches do you guys think I could take. A greedy algorithm gives a good solution, but certainly not the best solution. Feel free to look at my code, though it's awful. First real program in python.
 
Why do all C/C++ build systems suck? Make is arcane, but I think I might end up going back to it.

Nobody uses boost jam. QMAKE is full of magic. waf is almost ideal but too complicated to extend. Tup is Linux-only.

I have half a mind to write my own build system. Or, maybe I should learn cmake.
cmake is good. It's what I use for all my C++ projects.

Its documentation is garbage (or at least it was last I checked), but once you surmount that unnecessary and annoying obstacle you're in the clear. I have very few complaints about it.
 
Code:
''.join(reversed("y hello thar"))

boom

Code:
$ python -m timeit '"".join(reversed("the quick brown fox spent all day lurking neogaf."))'
1000000 loops, best of 3: 1.49 usec per loop
$ python -m timeit '"the quick brown fox spent all day lurking neogaf."[::-1]'
1000000 loops, best of 3: 0.188 usec per loop

Bam.
 

phoenixyz

Member
images.jpeg


Also, the slice version is much prettier ;)
 

Sandfox

Member
I'm starting a class on Assembly next week, and I was wondering if anyone had any tips for approaching the language on my own?

This class along with me putting in the time to get a better understanding of java, algorithms, and data structures should make for a fun semester lol.
 

NotBacon

Member
I prefer J

Code:
  |.'wat is this i dont even'
neve tnod i siht si taw

wat

I'm starting a class on Assembly next week, and I was wondering if anyone had any tips for approaching the language on my own?

This class along with me putting in the time to get a better understanding of java, algorithms, and data structures should make for a fun semester lol.

Well if you know what processor you'll be working with you can look up the spec sheet and manual for it to get a jumpstart.

In general, get really good at converting between hex, binary, and decimal. Also remember each instruction does only one single simple thing, nothing more.
 

leroidys

Member
wat



Well if you know what processor you'll be working with you can look up the spec sheet and manual for it to get a jumpstart.

In general, get really good at converting between hex, binary, and decimal. Also remember each instruction does only one single simple thing, nothing more.

That's good advice. Also read up on binary operators (definitely) and caching (if you have a chance).
 
I'm starting a class on Assembly next week, and I was wondering if anyone had any tips for approaching the language on my own?

This class along with me putting in the time to get a better understanding of java, algorithms, and data structures should make for a fun semester lol.

Pay more attention than I did in my ASM class back in college!
 

luoapp

Member
Spent this weekend writing a PopWords solver in python. PopWords is a game on the AppStore with a daily challenge...

So I spent some time with your code and was able to get about 2x speedup. The trick is to only do deepcopy when necessary.

Instead of
Code:
   newBoard = copy.deepcopy(board)
   newBoard[pos[0]][pos[1]] = '*'
   
   if (len(word) >= 3 and '*' in wordlist[charAtPos]):
      foundWords.append((word, newBoard))
   
   # keep searching the rest of the board with this letter removed
    ...

I did
Code:
   saveOne = board[pos[0]][pos[1]]
   board[pos[0]][pos[1]] = '*'

   if (len(word) >= 3 and '*' in wordlist[charAtPos]):
      newBoard = copy.deepcopy(board)
      foundWords.append((word, newBoard))
   
   # keep searching the rest of the board with this letter removed
    ...
   
   board[pos[0]][pos[1]] = saveOne
   return foundWords

BTW, there was a minor bug at line "if ( len(wordlist) >= 1 ):", it was "if ( len(wordlist) > 1 ):", which missed the last word in the dictionary.

It was kind of fun to practice reading someone else's code and a little bit python at the same time. Thanks for an interesting post.

PS: Turns out you can get rid of another deepcopy in minimize_board (do shallow copy only) yes, the result printout takes a bit to figure out ( need to read them backwards), but now it's about 1/3 of the original run time.
 

hateradio

The Most Dangerous Yes Man
For something that's supposed to make your life easier, it took me three days to get a Vagrant box to work right.

-_-

Hopefully it will continue to work well.
 

Slavik81

Member
For something that's supposed to make your life easier, it took me three days to get a Vagrant box to work right.

-_-

Hopefully it will continue to work well.
Building a vagrant box from scratch is a little tricky. It's quite nice for sharing environments among team members, though.
 

Anustart

Member
So I have to do a lab in an hour in a language I have 0 experience with, Python. I've brushed up for 15 minutes now and I've basically solved the problem with it already except for one little damn thing, and it's making me feel silly.

I have a this:

Code:
for x in range(0, 10):
        if x < 10:
            print("| %d |" % locations[x]),

Now I have an else: statement right after this, but I just cannot get the damn thing to just input a line break? What am I missing? Evidently my googling sucks because nothings working.
 

tuffy

Member
print() with a comma after it means to print the output without a newline. Omit the comma and it adds a newline. So something like print("") should do the trick.
 

BreakyBoy

o_O @_@ O_o
For something that's supposed to make your life easier, it took me three days to get a Vagrant box to work right.

-_-

Hopefully it will continue to work well.

Ops can be hard sometimes. If you need help, post about it. I do DevOps, and I use Vagrant nearly every day for testing different deployment scenarios. I might be able to help with the usual hangups with getting Vagrant to do what you want. And I'm pretty sure I'm not the only one here either.

That being said, it's all about Docker now. Oh we're back to bash now? That's cool.
 

hateradio

The Most Dangerous Yes Man
This is for a PHP box that I will use to manage a Laravel site. However, I used http://puphpet.com/ to generate a configuration for me.

The only issue I have now is that Xdebug is a huge fuck up. I've followed several guides on configuring it and making it work with PHPStorm, but it's flaky. I managed to make it work the first time, without issue. Then I tried to run it again later, and it wouldn't work. Then I tried following some other guides and nothing happened. I really, really hate that PHP doesn't have its own debugging feature. Makes me miss Visual Studio and ASP.NET. -_-

I had followed this, and it worked for a moment.
http://www.sitepoint.com/install-xdebug-phpstorm-vagrant/

Then I followed this, and it worked for a few hours yesterday.
http://www.mailbeyond.com/phpstorm-vagrant-install-xdebug-php

And today, I started a new box because I somehow accidentally erased the previous and, and it doesn't want to work. -__-

Note, that it actually works on the default vhost, localhost:80 or localhost:888 on the host machine. But the issue is when I try to reach my other vhost (which houses the Laravel site), nothing happens. Xdebug doesn't trigger for it at a consistent level. Even now, it's not reacting to anything I do.

I added this to the hosts file on the host machine, to reach it through a browser, and that works fine. I can see the site at http//app.dev. But to actually get it to debug has been crap.

Code:
192.168.56.101 app.dev

I hate you, Xdebug or Apache or whatever you are. Damn you, PHP!


Edit: Seems like Windows itself is an issue this case.

I modified the firewall to ignore the VM's adapter and it seems to work now. I imagine tomorrow everything will break again.

https://stackoverflow.com/questions/20914636/open-windows-firewall-for-xdebug
 

BreakyBoy

o_O @_@ O_o
Huh, I've never seen puphpet before. Neat idea. It seems to generate pretty clean Vagrant files too.

That being said, what you're doing should be pretty straightforward, so yeah as you already figured out, it doesn't seem like a Vagrant specific issue. Working with a Vagrant box, often the trickiest part is getting the networking bits to properly communicate between the VM, the host, and the outside world. Again though, it sounds like you were able to work it out.

I will do the snarky thing and say that you have reminded me of some of the reasons I'm glad I haven't done any PHP or Windows-specific work in a while. Mostly because I think I've blissfully forgotten a lot of the annoyances that were just par for the course for me before.

Of course, I suppose that now I'm just used to a different set of annoyances. Hey guys, how about that CoreOS?
 

NotBacon

Member
Any Android devs on here?

What's the best way to implement location auto complete?(in a AutoCompleteTextView). I'm using Google Places API right now, and it works well but seems very limiting at 1000 requests per day. Foursquare's API seems nice at 5000 per hour, but it seems limited to an area (so my user can't type any city in the world). I'm wondering if I should just use a local database at this point?
 

KageZero

Member
Hello, i want to ask is there any way to integrate aspectc++ into visual studio 2012. I have found a plugin for it but it's compatible only with vs2005 and the last version was released 7 years ago. Is something new available for it?
 

BreakyBoy

o_O @_@ O_o
Any Android devs on here?

What's the best way to implement location auto complete?(in a AutoCompleteTextView). I'm using Google Places API right now, and it works well but seems very limiting at 1000 requests per day. Foursquare's API seems nice at 5000 per hour, but it seems limited to an area (so my user can't type any city in the world). I'm wondering if I should just use a local database at this point?

I had to use Google Places API for a 1-day hackathon project a few weeks ago. I believe you can increase your quota on the Google Places API for free up to 10,000. You have to set up an actual account with them with a credit card so they can keep track of you though.

I'm waiting on a (voluntary) flight delay so I'll try and find the relevant info for you to kill some time.

Edit - Even better, it bumps you to 100,000 per day:
You can increase the above limit to 100&#8201;000 requests per 24 hour period by verifying your identity through the APIs console. A credit card is required for verification, by enabling billing in the console. We ask for your credit card purely to validate your identity. Your card will not be charged for use of the Places API.
 
Any Android devs on here?

What's the best way to implement location auto complete?(in a AutoCompleteTextView). I'm using Google Places API right now, and it works well but seems very limiting at 1000 requests per day. Foursquare's API seems nice at 5000 per hour, but it seems limited to an area (so my user can't type any city in the world). I'm wondering if I should just use a local database at this point?

Local db seems a little unmaintainable. How about running Google Places API through a caching server to limit requests? That way you could possibly get more bang for your buck per API request, whilst sending minimal data between the server and the device.
 

Lathentar

Looking for Pants
So I spent some time with your code and was able to get about 2x speedup. The trick is to only do deepcopy when necessary.

Instead of
Code:
   newBoard = copy.deepcopy(board)
   newBoard[pos[0]][pos[1]] = '*'
   
   if (len(word) >= 3 and '*' in wordlist[charAtPos]):
      foundWords.append((word, newBoard))
   
   # keep searching the rest of the board with this letter removed
    ...

I did
Code:
   saveOne = board[pos[0]][pos[1]]
   board[pos[0]][pos[1]] = '*'

   if (len(word) >= 3 and '*' in wordlist[charAtPos]):
      newBoard = copy.deepcopy(board)
      foundWords.append((word, newBoard))
   
   # keep searching the rest of the board with this letter removed
    ...
   
   board[pos[0]][pos[1]] = saveOne
   return foundWords

BTW, there was a minor bug at line "if ( len(wordlist) >= 1 ):", it was "if ( len(wordlist) > 1 ):", which missed the last word in the dictionary.

It was kind of fun to practice reading someone else's code and a little bit python at the same time. Thanks for an interesting post.

PS: Turns out you can get rid of another deepcopy in minimize_board (do shallow copy only) yes, the result printout takes a bit to figure out ( need to read them backwards), but now it's about 1/3 of the original run time.

Thanks for the great response. I'm not surprised there were some issues. Good job getting rid of a number of the deep copies, I'm sure there are ways to reduce it even more. However, to get the best solution for the problem the runtime is still too long. I'm pretty certain this is a problem that is exponential.

It was fun for my first crack at python. I'll probably rewrite it again to write more readable code, basically replacing all of the tuples with a class. It was getting difficult to remember where everything was supposed to go.

I'll probably them rewrite this again in D. I've been curious in that language for a while.

BTW. Nice catch on the len(wordlist) > 0 issue. It should probably be len(wordlist[charAtPos]) >= 1. Also, I think moving the deepcopy into the if statement causes another bug as you'll be writing the '*' into the board object, but not clearing it properly. The better change would be to only do a deep copy when appending to the foundWords and undoing the assignment to '*' for that character before the return statement. Thus you only make a deep copy of the board for completed words. This should dramatically reduce copies.
 

NotBacon

Member

Thanks!

Local db seems a little unmaintainable. How about running Google Places API through a caching server to limit requests? That way you could possibly get more bang for your buck per API request, whilst sending minimal data between the server and the device.

I actually wasn't planning on maintaining it since places don't really change :p

And a caching server would probably be a little overkill for this little project
 

luoapp

Member
Thanks for the great response. I'm not surprised there were some issues. Good job getting rid of a number of the deep copies, I'm sure there are ways to reduce it even more. However, to get the best solution for the problem the runtime is still too long. I'm pretty certain this is a problem that is exponential.

It was fun for my first crack at python. I'll probably rewrite it again to write more readable code, basically replacing all of the tuples with a class. It was getting difficult to remember where everything was supposed to go.

I'll probably them rewrite this again in D. I've been curious in that language for a while.

BTW. Nice catch on the len(wordlist) > 0 issue. It should probably be len(wordlist[charAtPos]) >= 1. Also, I think moving the deepcopy into the if statement causes another bug as you'll be writing the '*' into the board object, but not clearing it properly. The better change would be to only do a deep copy when appending to the foundWords and undoing the assignment to '*' for that character before the return statement. Thus you only make a deep copy of the board for completed words. This should dramatically reduce copies.

There are some improvements can still be made, e.g., better estimation of the value of remaining board, and faster stopping criteria for word searching, but the overall structure is pretty much set since you want the best solution. Switching to C++ and using some rudimentary data types (strings and arrays) should speed things up quite a bit (10x?). Another thing is to try make it parallel. That could be fun.
 

Everdred

Member
Does anyone know why I would get a Forbidden 403 error for the following URL:
u.php?n=eyelasers

But it works fine for other inputs like:
u.php?n=eyelase
u.php?n=dude

I've read a little about mod_security and I don't understand if it pertains to this.
 
Top Bottom