• 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

Hey guys.

I'm wondering if there are any good websites that put up programming problems to solve? I'd like to program more but I like having tasks to complete, and I usually can't come up with things myself.

A website that sorts the problems by difficulty would be extremely helpful. I do also have a C++ book for my class that I've been using to practice from.
 

harSon

Banned
Are you not initializing sum?

Isn't it initialized? Or do you mean setting sum equal to the formula before I enter the loop?

Y should start at 1, not 0; 3^0 = 1, so your first term is 1/(3*1) and not 1/(3*3), and the rest are similarly off.

Edit: beaten

Even after doing this, I'm still not getting the right answers. Here's what I have now:

Code:
#include <iostream>
#include <math.h>
#include <iomanip>

using namespace std;
int main()
{
    const int MAX_ITERATION = 21;
    double sum, totalSum;
    double x = 3;
    double y = 1;
    sum = (1.0/(x * pow(3,y)));

    for (int i = 0; i < MAX_ITERATION; i++, x = x + 2, y = y + 1)
    {

        if ((i % 2) == 0)
        {
            sum = sum + (1.0/(x * pow(3,y)));
            cout << sum << endl;
            cout << "X is " << x << endl;
            cout << "Y is " << y << endl;
        }
        else if ((i % 2) == 1)
        {
            sum = sum - (1.0/(x * pow(3,y)));
            cout << sum << endl;
            cout << "X is " << x << endl;
            cout << "Y is " << y << endl;
        }
    }

    totalSum = sqrt(12) * (1 - sum);

    cout << totalSum << endl;
}

Here's my output running the above code:
Code:
0.222222
X is 3
Y is 1
0.2
X is 5
Y is 2
0.205291
X is 7
Y is 3
0.203919
X is 9
Y is 4
0.204293
X is 11
Y is 5
0.204188
X is 13
Y is 6
0.204218
X is 15
Y is 7
0.204209
X is 17
Y is 8
0.204212
X is 19
Y is 9
0.204211
X is 21
Y is 10
0.204211
X is 23
Y is 11
0.204211
X is 25
Y is 12
0.204211
X is 27
Y is 13
0.204211
X is 29
Y is 14
0.204211
X is 31
Y is 15
0.204211
X is 33
Y is 16
0.204211
X is 35
Y is 17
0.204211
X is 37
Y is 18
0.204211
X is 39
Y is 19
0.204211
X is 41
Y is 20
0.204211
X is 43
Y is 21
2.75669

I'm sure it's something easy, but I'm completely loss right now x_x
 

Barzul

Member
Hey guys is code academy a good way to learn code. Teaching myself Python on there and it seems pretty good so far. I do have some programming background as I took a Java class, but I've honestly forgotten most of it. I do remember the basics and will be jumping back into that if learning Python on CA proves successful.
 

AcousticLemmon

Neo Member
harSon, I'm a little iffy on the math, but I think you need to iterate your x and y variables after calculating the initial sum but before the for loop.

The way it's structured they are only iterated after it does the initial cycle of the for loop, which means the values are the same for two cycles of calculations.
 

tokkun

Member
Hey guys.

I'm wondering if there are any good websites that put up programming problems to solve? I'd like to program more but I like having tasks to complete, and I usually can't come up with things myself.

A website that sorts the problems by difficulty would be extremely helpful. I do also have a C++ book for my class that I've been using to practice from.

Go to the TopCoder community site and look at their algorithm challenges. I'd give you a direct link, but their site is such a pain in the ass to navigate.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Hey guys.

I'm wondering if there are any good websites that put up programming problems to solve? I'd like to program more but I like having tasks to complete, and I usually can't come up with things myself.

A website that sorts the problems by difficulty would be extremely helpful. I do also have a C++ book for my class that I've been using to practice from.

Project Euler
This site has math problems that you can utilize programming to solve.
 

injurai

Banned
Haha, Just saw this on Google+

Nice one JetBrains, gotta love them turning Apples mistake into a marketing opportunity :D

3V5Co97.jpg

that's amazing. Outside of VS, IntelliJ is GOAT IDE.
 

harSon

Banned
Look at your series and ask if this makes sense.

Hint: .2222222... = 1/9 * 2

I got the actual formula to work:
Code:
#include <iostream>
#include <math.h>
#include <iomanip>

using namespace std;
int main()
{
    const int MAX_ITERATION = 21;
    double sum, totalSum;
    double x = 1;
    double y = 0;
    sum = (1.0/(x * pow(3,y)));

    for (int i = 0; i < MAX_ITERATION; i++)
    {
        x = x + 2;
        y = y + 1;

        if ((i % 2) == 0)
        {
            sum = (1/(x * pow(3,y)));
            cout << sum << endl;
            cout << "X is " << x << endl;
            cout << "Y is " << y << endl;
        }
        else if ((i % 2) == 1)
        {
            sum = (1.0/(x * pow(3,y)));
            cout << sum << endl;
            cout << "X is " << x << endl;
            cout << "Y is " << y << endl;
        }
    }

    totalSum = sqrt(12) * sum;

    cout << totalSum << endl;
}

But I'm not sure how to implement the switching of opperators between addition and subtraction to satisfy this formula:

6c17e102a2b48bd9d01dcbb77985ac67.png


I was trying to use the modulo operator to do it, as can be seen in some previous examples, but I can't get it to work within my for loop. Any ideas on how to get it to work, or other ways I could accomplish it within a for loop?
 

Exuro

Member
So I'm about to finish up the shell project I've been working on. I just need some help on getting my pipe up and running. All of the error checking is taken care of so I'm just trying to get the piping to work correctly.

I need to pipe recursively so how would I check to see if there is anything in the pipe? I run whatever command in child and when it returns to the parent I need to do a conditional check on if the pipe was used so I can recurse or not. What's the way to do this?
 

harSon

Banned
Ugh, I just can't get this to work.

I had another idea to just set a variable equal to 1, and simply multiply that by -1 every loop to alternate between addition and subtraction like so:

Code:
#include <iostream>
#include <math.h>
#include <iomanip>

using namespace std;
int main()
{
    double sum, totalSum;
    int sign = 1;
    int x = 3;
    int y = 1;
    sum = sign * (1 / (x * pow(3,y)));

    for (int i = 0; i < 21; i++)
    {
        x = x + 2;
        y = y + 1;
        sum += (sign * (1 / (x * pow(3,y))));
        sign *= -1;
        cout << "X is " << x << endl;
        cout << "Y is " << y << endl;
        cout << "I is " << i << endl;
        cout << sum << endl;
    }
    totalSum = sqrt(12) * sum;
    cout << totalSum << endl;
}

I've been at this for hours now, and I just can't get it to work... I could really use a major hint right about now :/
 
Ugh, I just can't get this to work.

I had another idea to just set a variable equal to 1, and simply multiply that by -1 every loop to alternate between addition and subtraction like so:

I've been at this for hours now, and I just can't get it to work... I could really use a major hint right about now :/

Why do you need this? With each iteration you are calculating a sum that can be either positive or negative depending on pow(-3, k). If k = 0 to infinity you get 1, -3, 9, ...

So leave your original idea with 1 - sum. Just remember that you need to add up each iteration of the sums you calculate. So sum = + (-1/9) + (+1/27) + (-1/135) + etc. Then after x iterations you get a negative value for sum. So you have to "add" it to 1 instead of subtracting it.

I tested this yesterday - if you really change y, initialize sum = 0 and instead of (1 - sum) use (1 + sum) because (1 + (-sum) is what you want your code works.

Edit: Just use 5 iterations and use a breakpoint on the for-loop and step into it. You see how your variable change and how the sum is calculated. Maybe make the first few iterations on paper aswell so you see where your code differs from the solution.
 
Hey guys.

I'm wondering if there are any good websites that put up programming problems to solve? I'd like to program more but I like having tasks to complete, and I usually can't come up with things myself.

A website that sorts the problems by difficulty would be extremely helpful. I do also have a C++ book for my class that I've been using to practice from.

There's a few:
Project Euler has already been named.
http://rosalind.info/ for computational biology (lots of string processing, DNA stuff)
http://programmingpraxis.com/ mostly has math-y or algorithm stuff (implementing data structures)
http://www.codewars.com/ works in your browser but only works for Ruby, Coffeescript and Javascript so far (Python support is coming soon apparently)
http://coderbyte.com/ I just found this while googling, never tried it myself.
 
I've been at this for hours now, and I just can't get it to work... I could really use a major hint right about now :/

Uh, you're not following the formula anymore. That code calculates: &#8730;(12) * (1/9 + 1/45 - 1/189 + ... )

And not: &#8730;(12) * (1 - 1/9 + 1/45 - 1/189 + ...)
 

usea

Member
You have to pay for a lot of them though.
Aren't they pretty cheap? WebStorm is only $99 for developers at companies, $49 for individuals or startups, and $29 for students. PyCharm is a little more ($199 / 99 / $29). But the free versions are pretty great too, just like Visual Studio.

Compare that to Sublime Text which is $70 and it's just an editor. Or Visual Studio which is an order of magnitude or two higher.

Anyway, I just think they're good IDEs.

There's a few:
Project Euler has already been named.
http://rosalind.info/ for computational biology (lots of string processing, DNA stuff)
http://programmingpraxis.com/ mostly has math-y or algorithm stuff (implementing data structures)
http://www.codewars.com/ works in your browser but only works for Ruby, Coffeescript and Javascript so far (Python support is coming soon apparently)
http://coderbyte.com/ I just found this while googling, never tried it myself.
Some other good ones are
https://www.hackerrank.com/ categorized problems with automatic scoring and leaderboards, in various languages
http://code.google.com/codejam/contests.html practice old google code jam problems. automatic scoring
 
I use Visual Studio with Windows and QTCreator with Debian. Both are in my case free - QTCreator anyways and I get Visual Studio via Dreamspark.
 
Okay, Programming GAF either I'm suffering from lack of sleep or I'm just not thinking right.
So, my assignment is pretty straight forward it is:


Write a program that will search strings “bat”, “cat”, “fat”, and “hat”. You have to read from example.txt file (uploaded in blackboard) and output which of these keywords are present in the file. Also, output which keywords are not present.

Here is my code so far:
Code:
#include <string>
#include <iostream>
#include <fstream>
#include <cstddef>
using namespace std;

int main()
{
    
    ifstream input( "//Users//Rico//Downloads//example.txt" ) ;
    string search_str1 = "bat";
    string search_str2 = "fat";
    string search_str3 = "cat";
    string search_str4 = "hat";
    
    string line ;
    int keyWords = 0 ;
    int otherWords = 0;
    getline( input, line ) ;
    size_t found = line.find(search_str1);

    
    
    return 0;
    

}


My first problem so far is, I was thinking "find" would aid me in solving my problem, yet all find does is return the index.

Secondly, is there an easier way to allocate just one "string" with the keywords(bat,hat,cat,fat).
 

Slavik81

Member
You can create an array of strings like so:
Code:
string search_strs[] = { "bat", "fat", /* and so on */ };

In the example file, how are the words separated? The easiest way of tackling the problem is probably to break the entire file down into a std::vector of words, then look through that vector for your search strings. There are more efficient ways to do it, but that one breaks the task up into a couple of very clearly defined steps with easily verified inputs and outputs.
 

tokkun

Member
My first problem so far is, I was thinking "find" would aid me in solving my problem, yet all find does is return the index.

Secondly, is there an easier way to allocate just one "string" with the keywords(bat,hat,cat,fat).

string::find() returns the static value string::npos if the string you are searching for is not present.

So you just do

Code:
if (my_str.find(search_term) != string::npos) {
  //...
}
 

Slavik81

Member
It's worth mentioning that tokkun made a different assumption than me. I presumed that "keywords are present in the file" means that "bat" shouldn't match the phrase "hand to hand combat", while he presumed that it should.
 

Water

Member
It's worth mentioning that tokkun made a different assumption than me. I presumed that "keywords are present in the file" means that "bat" shouldn't match the phrase "hand to hand combat", while he presumed that it should.
And if it should match substrings regardless of whitespace, as tokkun presumed, there is still the question of whether this is supposed to be a count of all instances of substring, or only non-overlapping instances. In other words: does the assignment expect this to print 1 or 2? (edit: actually doesn't matter since the specific strings given in the assignment can't overlap...)
Code:
cout << count_substring("xxx", "xx") << endl;
In any case, it would clarify things if you first wrapped this in a function so you can handle all the cases neatly:
Code:
size_t count_substring(const std::string& str, const std::string& sub) {                                
    // ...
}

int main() {
    auto substrings = {"bat", "cat", "fat", "hat"};
    auto counts = unordered_map<string, size_t>();
    // ... read from file; for every line you read:
    for (const auto& s : substrings) {
        counts[s] += count_substring(line, s);
    }
    // ... finally print the counts
}
 

Harpuia

Member
EDIT: I (sadly) found the error. Set_Size checks to see if our current size is 0. Yet by that point, it hasn't been set to anything, so it'll delete a matrix that hasn't even been created yet.
 
Anyone with experience with xmldom or xmlminidom? I have an annoying issue. My data is set up as such

Code:
<Category>text</Category>
<Category>text</Category>
<Category>text</Category>
<Location>text</Location>
<Country>USA</Country>
<Description>TEXTtextTexttext</Description>

as a part of a larger set of xml tags.

Now I can read them all in correctly and output the text correctly by using

getElementsByTagName(string)

and then looping through each object tag and using

object.childNodes[0].nodeValue

and it works correctly for each one, except the description tag which gives me an out of range error on childNodes[0]. object.firstChild works but I get a memory address with that.
 

Exuro

Member
Okay I found what the problem is. Of course it was code that the TA gave me to use.

I need to wait at some point and clean out all child processes. I was using

/*while(wait(-1, NULL, WNOHANG) != -1)
{
printf("Killing Zombies");
}*/

But it doesn't seem to work at all.

Does anyone know another method to get this to work?
 
That's probably because firstChild is an element itself. It would have a nodeValue.


Unless I did something wrong python gives me an attribute error when I do object.firstChild.nodeValue: 'NoneType' object has no attribute 'nodeValue' so that's why I'm confused as to why neither of them work when it works for all others.

edit:

checking if it has child notes: object.hasChildNodes() returns true so why the fuck can I not actually access the child node.

and object.toxml() works and gives me the full description tag and text elements in it. what the hell.
 
I hope this isn't the wrong place to put this...

I've been working on a programming portfolio of my past work for any potential future jobs, internships, and whatnot. While I am currently a student, I figured that a portfolio would help legitimize myself if I tried to apply for a job in programming without a degree.

I am quite nervous about it because my projects aren't amazing or anything. I try to hype myself up and show pride in my work without getting too wordy. Also, I'm neither a web developer or designer. I did write the HTML by myself (and it *almost* validates, yay), but the design is kind of ugly and a work in progress...

Anyway, it is here:

Is it any good?
 

Zutroy

Member
I'm not new to programming but I'm not exactly confident either. I'm trying to do something and I'm just completely stuck, so I was wondering if anyone could help.

I'm using a streamread to load data from a text file that's laid out as follows (tab separated)
Code:
int  int  dub  int  int
1    2    3.5    4    5
6    7    8.5    9    10
etc.
I need to store all this data, identify each line, and process the values later on.

The closest I've got is to use a dictionary with an int and string, hoping that I could then maybe split the data up later to process, but it seems to remove the tab so it's storing it like follows
Code:
K:1 V:123.545
K:2 V:678.5910
etc.

I feel completely stuck now though, any suggestions of a better way to store it?

[E] C# btw
 

Water

Member
Is it any good?
First reaction: finished game in app store distribution? Good sign!

Then it gets a little iffier. The whole site is obviously written to advertise you to an employer, and one page is dedicated to telling about yourself, yet there's no CV or resume in sight, or any word of your current employment/education status; it's suspicious as hell. That problem can be fixed by simply starting off your introduction by saying you are a student in XXX and expect to graduate in 201X. While you are at it, rewrite the rest of the introduction or take it to someone you know is good at writing, because it's awkward now. Brief is good. What you did when you were 10 doesn't belong in your introduction.

Like you said, you are not a designer. I'd switch to a professional page template/framework. It'll look a ton better, and you'll look more technically proficient for using one vs. hand-rolled so-so HTML. Using the right tool for the job is an important quality in a programmer. If you want to show your web programming chops, do something at the server end.

Finally, it wouldn't hurt to see some actual code in there.
 

Ah, that is very helpful, thank you.

Since I was focusing more on the portfolio page, I didn't put much thought into the "about me" section yet. However, I did choppily copy/paste my writing around because of this article I saw. In short, it mentions not putting education on the forefront and instead suggests writing about what makes you unique first. That said, you make a great point about the iffiness, so I'll reconsider that...

Also, I figured that it would look odd if I didn't code my site and instead used a site builder or another tool, but you make a good point about using the right tool for the job.

As for adding code to the portfolio, I've read in several places that it's a smart thing to do, but I don't have any interesting or ground-breaking code to add, so I just skipped it. I'll try to think of something...
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Ah, that is very helpful, thank you.

Since I was focusing more on the portfolio page, I didn't put much thought into the "about me" section yet. However, I did choppily copy/paste my writing around because of this article I saw. In short, it mentions not putting education on the forefront and instead suggests writing about what makes you unique first. However, you make a great point about the iffiness, so I'll reconsider that...

Also, I figured that it would look odd if I didn't code my site and instead used a site builder or another tool, but you make a good point about using the right tool for the job.

As for adding code to the portfolio, I've read in several places that it's a smart thing to do, but I don't have any interesting or ground-breaking code to add, so I just skipped it. I'll try to think of something...

I think you should use a site builder, unless you are looking to go into a web development job. And even then it may be more beneficial to show off you design prowess through a site builder rather than scrape together a handwritten site.

If you put the source code from your apps/programs you made up on GitHub or something similar (I'm assuming you aren't making money off the apps), then you can link those repositories and show off your coding style.

Just my 2cents.
 
Doesn't need to be groundbreaking code but let the people see how you handle problems (*), use coding standard, comments, ...

(*) like using case statements instead of if-else, error handling and so on.
 
Unless I did something wrong python gives me an attribute error when I do object.firstChild.nodeValue: 'NoneType' object has no attribute 'nodeValue' so that's why I'm confused as to why neither of them work when it works for all others.

edit:

checking if it has child notes: object.hasChildNodes() returns true so why the fuck can I not actually access the child node.

and object.toxml() works and gives me the full description tag and text elements in it. what the hell.

Figured out my issue. In the dtd it never specifies if the description tag would be empty or nonexistent so there was one element in my data that doesn't have one and that was throwing the whole thing off. Bleh.
 

Water

Member
Doesn't need to be groundbreaking code but let the people see how you handle problems (*), use coding standard, comments, ...

(*) like using case statements instead of if-else, error handling and so on.
Besides the quality of the code itself, showing the complete set of files for a project (even if small) on Github/Bitbucket/etc. can also simultaneously demonstrate you know how to use industry standard tools like version control, build control and so on.
 
Is it any good?

Just having an online portfolio puts you ahead of a lot of other people, but I agree with the feedback others have given. A small addition, but I'm not sure if you need the subtitles under the headings "Completed Projects" and "Incomplete Projects" - I don't think they need any more explanation.

I figured that it would look odd if I didn't code my site and instead used a site builder or another tool

As as the already-acknowledged point that you should use the right tool for the job, trying to do everything yourself isn't necessary good or more impressive. Building on top of tools or other people's work shows that you know your strengths and weaknesses, and are able to use/learn existing things to work faster/better. There are no jobs where you'll be building everything from scratch anyway.

Anyway, that's my little addition. Take with a grain of salt, I'm hardly experienced myself.
 
Hi guys,

I am writing this on behalf of a friend who needs some help.

My friend has to write a UDP chat program. Here is the code he has so far.

Server
Code:
package udpserver;

import java.io.*;
import java.net.*;

public class udpServer {
    
    public static void main(String[] args) {
        try {
            DatagramSocket Serversock = new DatagramSocket(5678);
            BufferedReader in1 = new BufferedReader(new InputStreamReader(System.in));
            
            String st1;
            while(true) {
                byte[] send_data1 = new byte[1024];
                byte[] receive_data1 = new byte[1024];
                DatagramPacket receive_packet1 = new DatagramPacket(receive_data1, receive_data1.length);
                Serversock.receive(receive_packet1);
                String str1 = null;
                
                str1 = new String(receive_packet1.getData());
                System.out.println("Received from client...");
                System.out.println(str1.trim());
                
                System.out.println("Enter the string...");
                st1 = in1.readLine();
                
                if(st1.equals("quit")) {
                    Serversock.close();
                }
                send_data1 = st1.getBytes();
                InetAddress ad1 = receive_packet1.getAddress();
                int p1 = receive_packet1.getPort();
                DatagramPacket send_packet1 = new DatagramPacket(send_data1, send_data1.length, ad1, p1);
                Serversock.send(send_packet1);
                
                
            }
        }
        catch(Exception e) {
            System.out.println(e);
        }
    
    }
}

Client
Code:
package udpchat;

import java.io.*;
import java.net.*;
       
public class udpClient {

    public static void main(String[] args) {
        try {
            DatagramSocket Clientsock = new DatagramSocket();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            
            String str1;
            while(true) {
                byte[] send_data = new byte[1024];
                byte[] receive_data = new byte[1024];
                System.out.println("Enter the string...");
                str1 = in.readLine();
                if(str1.equals("quit")) {
                    Clientsock.close();
                }
                send_data = str1.getBytes();
                InetAddress addr = InetAddress.getLocalHost();
                DatagramPacket send_packet = new DatagramPacket(send_data,send_data.length,addr,5678);
                Clientsock.send(send_packet);
                
                DatagramPacket receive_packet = new DatagramPacket(receive_data,receive_data.length);
                Clientsock.receive(receive_packet);
                String s1 = new String(receive_packet.getData());
                System.out.println("The string recieved back from the server..." + s1.trim());
                
            }
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}


He has to add a checksum like behavior to the program(something like writing the length of the message before the message and having the client verify it upon arrival) and an encryption/decryption algorithm as well. I have suggested that he use something like the Caesar cipher for the encryption/decryption. My friend would appreciate any advice or help you guys could give him on how to implement the checksum and encryption/decryption. I would help him but I myself am not that good at programming.
 

Tristam

Member
I have a usability question regarding an undo/redo framework I'm implementing in my GUI application. My application consists of a 3-level tree diagram to the side whose nodes are represented by corresponding tab pages (which can be hidden/shown by the user) in the central workspace, so the UI looks quite similar to Visual C++ 2008. However, unlike it and quite a few other tabbed applications (MS OneNote, Notepad++, etc.), tabs are *not* their own documents. Only the top-level nodes represent actual files. Thus, my plan is to have a unified undo/redo stack in the same way that, say, MS Excel does. The catch is that multiple documents can be open simultaneously in the same window (each represented by, as I mentioned, a top-level tree node), whereas that is not the case in Excel.

So, I see two options regarding the undo/redo stack implementation:
1.) Have a universal undo stack for everything, spanning multiple files.
2.) Have one undo stack only for each file.

Option 2 seems logical and consistent with other behaviors -- e.g., a 'save' action only applies to one file, and there's additionally a 'save all' action -- but it also seems that it can be somewhat confusing given that the tabs whose roots are in disparate top-level nodes can be open simultaneously and side-by-side. Option 1, by contrast, is less consistent but despite that removes any confusion.

As users and as developers, what do you think best?
 
Top Bottom