• 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

Granadier

Is currently on Stage 1: Denial regarding the service game future
Yeah, I forgot to specify the IP address the client should connect to. It's working now.


Yes to the bolded. Smart boards and the like are really cool, but as long as there's delay I'll always prefer a physical whiteboard.

This is tough too since most of the delay is from the hardware itself.
 

Slavik81

Member
Random question, but the mention of a whiteboard sparked it into my head.
A while ago I created a browser-based digital whiteboard that we use every day at work for drawing out ideas. It's touch based and works fairly well. (we have some large touch screens on the walls)
Unfortunately, this gets unusably slow after about 15 seconds of drawing in FireFox (37.0.1, Ubuntu 14.04).

There's been people that have told me they still prefer a traditional whiteboard though. That the feeling of using a marker on a whiteboard is more satisfying or natural.
It's made me think of the whole digital/analog world change a little bit, and how such simple things like that just do not feel right. Maybe it's the ever so tiny delay that most digital things have, especially in touch tech, or something else. I'm assuming there are people out there getting paid exponentially more than I am to figure these things out.

Ok that was rambling. What are your opinions on the whole using something digitally vs. traditional analog? ie: taking notes, whiteboarding, reading
This is basically what SMART is all about. My impression is that everyone likes Smartboards in theory, but hates them in practice.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Unfortunately, this gets unusably slow after about 15 seconds of drawing in FireFox (37.0.1, Ubuntu 14.04).


This is basically what SMART is all about. My impression is that everyone likes Smartboards in theory, but hates them in practice.

Is this 15 seconds of continuous drawing, and then it slows down after you let off the mouse button?

Also what hardware is in the machine you were encountering the slowdown on?

edit: Just tested and replicated the slowdown on Firefox w/OSX. I think the reason this is happening is because the library I'm using (paper.js) treats the drawing as paths, and subsequently stores the path data in a giant path array.

This is weird, and I think something to do with whatever way Firefox handles drawing.
I tested Chrome, Firefox, and Safari with 30s drawing times and checked the path sizes afterwards.

Chrome 43.0.2357.37 beta : 30s drawing : 896 path items : no slowdown
Safari 8.0.5 : 30s drawing : 852 path items : no slowdown
Firefox 39.0a2 dev edition: 30s drawing : 725 path items : major slowdown

This was developed as an inhouse project that I decided to include in my portfolio. We all use Chrome/Safari at work, and I never ended up testing huge path arrays on Firefox.
 
Ok, very odd question time. I've been building a program that acts as a proxy server and finally got it to work right. However, when I added multi-threaded capability the connections were refused before the accept() call even saw them. Bear in mind the threads aren't created until after the connection from the client is accepted. Anybody have any idea what's causing this? With it being a school assignment I'd rather PM code than paste it here.
 
OpenGL display lists

ibMCsO.jpg
 

jrush64

Banned
Hi programming OT, I'm new to programming and Unity and I have a problem that I can't seem to solve.


Let me break it down, please bear with me.

Basically there are 4 switches - Switch 1, Switch 2, Switch 3, Switch 4.
2 Gates - Gate 1 and Gate 2
1 Platform
1 Cage

This is the way the logic is supposed to work and the order.

- You press Switch 1 with Character 1, and Platform 1 on character 2's side, starts moving, but a cage locks Character 1 in. So you switch to Character 2. Character 2 can't get to switch 3 until platform 1 starts moving.

- Character 2 presses switch 3 which opens gate 1. Character 1 is still locked in.

- After switch 3 is pressed, Character 2 goes to switch 4 which opens the cage.

- Then character 2 presses switch 2 which opens gate 2 for character two.

This is the order:

- Switch 1, moves platform
- Switch 3 opens gate 1
- Switch 4 opens cage
- Switch 2 opens gate 2

Code:
public bool SwitchOne;
    public bool SwitchTwo;
    public bool SwitchThree;
    public bool SwitchFour;
    public bool SidePlatformOne;
    public bool SidePlatformTwo;
    public bool UpDownOne;
    public    GameObject platform;
    public    GameObject gate;
    public    GameObject cage;
    public bool CageOne;
    private Animator anim;
    private Animator animone;
    private Animator animtwo;
    public bool gateone;
    public bool gatetwo;
   
    // Use this for initialization
    void Start () {
       
        anim = platform.GetComponent<Animator>();
        animone = gate.GetComponent<Animator>();
        animtwo = cage.GetComponent<Animator>();    
       
    }
   
    // Update is called once per frame
    void Update () {
       
    }
   
    void OnTriggerEnter (Collider other)
    {
       
        if (gameObject.tag == "SwitchOne")
        {          
            SwitchOne = true;
            SidePlatformTwo = true;
            anim.SetTrigger ("SidePlatformTwo");
           
            if((SwitchOne == true) && (SidePlatformTwo == true))
            {
                CageOne = true;
                animtwo.SetTrigger ("GateBlockOne");    //Block's Tarro In and activates  her platform    
               
            }
        }
       
       
        if(gameObject.tag == "SwitchTwo")
        {
            SwitchTwo = true;
        }
            if((SwitchTwo == true) && (gateone == true) && (SwitchThree == true))
            {
                gatetwo = true;
                animone.SetTrigger ("GateTwoLevelTwo");
            }
 
       
        if(gameObject.tag == "SwitchThree")
        {
            SwitchThree = true;
        }
            if((SwitchThree == true) && (CageOne == true))
            {
                gateone = true;
                animone.SetTrigger ("GateOneLevelTwo");
            }
 
       
        if(gameObject.tag == "SwitchFour")
        {
            SwitchFour = true;
        }
            if((SwitchFour == true) && (SwitchThree == true))
            {
                CageOne = false;
            }    
       
       
    }
   
}
I've checked everything, added debug log. The code that executes the gate open logic doesn't work. The gate is supposed to open as soon as switch 1 and switch 3 are pressed. But it doesn't work.

I have no idea what to do anymore.

I'm a major noob as i just started 3 months ago and would really realy appreciate the help. Thanks

Never mind, issue has been resolved. Thanks for reading.
 
Hi programming OT, I'm new to programming and Unity and I have a problem that I can't seem to solve.


Let me break it down, please bear with me.

Basically there are 4 switches - Switch 1, Switch 2, Switch 3, Switch 4.
2 Gates - Gate 1 and Gate 2
1 Platform
1 Cage

This is the way the logic is supposed to work and the order.

- You press Switch 1 with Character 1, and Platform 1 on character 2's side, starts moving, but a cage locks Character 1 in. So you switch to Character 2. Character 2 can't get to switch 3 until platform 1 starts moving.

- Character 2 presses switch 3 which opens gate 1. Character 1 is still locked in.

- After switch 3 is pressed, Character 2 goes to switch 4 which opens the cage.

- Then character 2 presses switch 2 which opens gate 2 for character two.

This is the order:

- Switch 1, moves platform
- Switch 3 opens gate 1
- Switch 4 opens cage
- Switch 2 opens gate 2

Code:
public bool SwitchOne;
    public bool SwitchTwo;
    public bool SwitchThree;
    public bool SwitchFour;
    public bool SidePlatformOne;
    public bool SidePlatformTwo;
    public bool UpDownOne;
    public    GameObject platform;
    public    GameObject gate;
    public    GameObject cage;
    public bool CageOne;
    private Animator anim;
    private Animator animone;
    private Animator animtwo;
    public bool gateone;
    public bool gatetwo;
   
    // Use this for initialization
    void Start () {
       
        anim = platform.GetComponent<Animator>();
        animone = gate.GetComponent<Animator>();
        animtwo = cage.GetComponent<Animator>();    
       
    }
   
    // Update is called once per frame
    void Update () {
       
    }
   
    void OnTriggerEnter (Collider other)
    {
       
        if (gameObject.tag == "SwitchOne")
        {          
            SwitchOne = true;
            SidePlatformTwo = true;
            anim.SetTrigger ("SidePlatformTwo");
           
            if((SwitchOne == true) && (SidePlatformTwo == true))
            {
                CageOne = true;
                animtwo.SetTrigger ("GateBlockOne");    //Block's Tarro In and activates  her platform    
               
            }
        }
       
       
        if(gameObject.tag == "SwitchTwo")
        {
            SwitchTwo = true;
        }
            if((SwitchTwo == true) && (gateone == true) && (SwitchThree == true))
            {
                gatetwo = true;
                animone.SetTrigger ("GateTwoLevelTwo");
            }
 
       
        if(gameObject.tag == "SwitchThree")
        {
            SwitchThree = true;
        }
            if((SwitchThree == true) && (CageOne == true))
            {
                gateone = true;
                animone.SetTrigger ("GateOneLevelTwo");
            }
 
       
        if(gameObject.tag == "SwitchFour")
        {
            SwitchFour = true;
        }
            if((SwitchFour == true) && (SwitchThree == true))
            {
                CageOne = false;
            }    
       
       
    }
   
}
I've checked everything, added debug log. The code that executes the gate open logic doesn't work. The gate is supposed to open as soon as switch 1 and switch 3 are pressed. But it doesn't work.

I have no idea what to do anymore.

I'm a major noob as i just started 3 months ago and would really realy appreciate the help. Thanks

Never mind, issue has been resolved. Thanks for reading.

Just a helpful note, but I believe there's a way to correct indentation in Monodevelop, that can help when you run into issues like this.

I think its Edit->Format->Format document.

But yeah, like the guy above me mentioned, your indentation is likely leading you to reading the code slightly wrong.
 
I'm having some issues with Hibernate. I've got a User class that has, among other things, a List<User> as a list of friends. This is how I've got it set up:
Code:
    @Column(name = "user_id")
    @Id
    @GeneratedValue
    public long getId() {
        return id;
    }

    ...

    @ManyToMany
    @JoinTable(name = "user_friends",
            joinColumns = @JoinColumn(name = "first_id", referencedColumnName = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "second_id", referencedColumnName = "user_id"))
    public List<User> getFriends() {
        return friends;
    }
The issue I'm having is updating the relation. I can create a user with no friends just fine, but when I want to update it, like the following, the user_friends relation always stays empty.

Code:
    public void addFriend(User user, User friend) {
        user.addFriend(friend);
        friend.addFriend(user);
        currentSession().beginTransaction();
        currentSession().update(friend);
        currentSession().update(user);
        currentSession().getTransaction().commit();
    }

I'm still pretty new to Hibernate and most of this I've grabbed from tutorials and example code. I'm suspecting the issue is in the addFriend method, but I'm not sure what the problem is.

edit: I've now also enabled CascadeType.ALL on the friends relation and I'm logging out the Hibernate SQL statements. Setting the cascade option didn't help and unsurprisingly, Hibernate is not doing any updates or inserts when I try to add a user as a friend.

edit 2: Here's the generated SQL for creating the relevant tables, looks like what it should:
Code:
create table user_friends (first_id bigint not null, second_id bigint not null)
create table users (user_id bigint not null, hashedPassword varchar(255), name varchar(255), primary key (user_id))
alter table users add constraint UK_3g1j96g94xpk3lpxl2qbl985x  unique (name)
alter table user_friends add constraint FK_mpngi85uyhop9v3h396vkhy2e foreign key (second_id) references users
alter table user_friends add constraint FK_2uhtibhit7vnwwlueneaf8h0b foreign key (first_id) references users
create sequence hibernate_sequence start with 1 increment by 1
 

Qurupeke

Member
This week I was working on my first "big" project in C and that's certainly how I feel:

"My code works and I don't know why"

It's a list that has a list that has a struct, which has a struct, date structs, integers, strings and another list, which has a struct with a struct in it. Or something like that, I really can't describe it. And you have to read a file to obtain the infos. Considering that till now the only thing I did was solving math/logic problems using C, this feels quite harder. The good thing is, for now, I fix all the errors but I really have no idea what I do, quite a few times.
 

Skittles

Member
I'm having some issues with Hibernate. I've got a User class that has, among other things, a List<User> as a list of friends. This is how I've got it set up:
Code:
    @Column(name = "user_id")
    @Id
    @GeneratedValue
    public long getId() {
        return id;
    }

    ...

    @ManyToMany
    @JoinTable(name = "user_friends",
            joinColumns = @JoinColumn(name = "first_id", referencedColumnName = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "second_id", referencedColumnName = "user_id"))
    public List<User> getFriends() {
        return friends;
    }
The issue I'm having is updating the relation. I can create a user with no friends just fine, but when I want to update it, like the following, the user_friends relation always stays empty.

Code:
    public void addFriend(User user, User friend) {
        user.addFriend(friend);
        friend.addFriend(user);
        currentSession().beginTransaction();
        currentSession().update(friend);
        currentSession().update(user);
        currentSession().getTransaction().commit();
    }

I'm still pretty new to Hibernate and most of this I've grabbed from tutorials and example code. I'm suspecting the issue is in the addFriend method, but I'm not sure what the problem is.

edit: I've now also enabled CascadeType.ALL on the friends relation and I'm logging out the Hibernate SQL statements. Setting the cascade option didn't help and unsurprisingly, Hibernate is not doing any updates or inserts when I try to add a user as a friend.

edit 2: Here's the generated SQL for creating the relevant tables, looks like what it should:
Code:
create table user_friends (first_id bigint not null, second_id bigint not null)
create table users (user_id bigint not null, hashedPassword varchar(255), name varchar(255), primary key (user_id))
alter table users add constraint UK_3g1j96g94xpk3lpxl2qbl985x  unique (name)
alter table user_friends add constraint FK_mpngi85uyhop9v3h396vkhy2e foreign key (second_id) references users
alter table user_friends add constraint FK_2uhtibhit7vnwwlueneaf8h0b foreign key (first_id) references users
create sequence hibernate_sequence start with 1 increment by 1
I'm ignorant about hibernate (java code right?) but are you endlessly calling "addfriend" recursively in the addfriend function?
 
I'm ignorant about hibernate (java code right?) but are you endlessly calling "addfriend" recursively in the addfriend function?

Oh, I see how you could think that, the naming is confusing here. No, there's an addFriend method (all this does is add another user to the user's friends list) for the User class and the addFriend(User, User) method that's in the UserDAO class, which is the one that I've posted.
 

Slavik81

Member
I did about 20 hours of work in the past 24 hours. I was glad to be back in school doing cool projects for each class, but now I'm glad I'm done with classes for the rest of my master's. I can't keep doing this...
 
Right, because C++ is just what apps need and devs want. Should've bought Xamarin instead. C# is the way to go.

C++ is in fact what many apps and devs need and want. Maybe not all, but some. And Microsoft actually is making a big push on C#. They open sourced the CoreCLR and have it running on FreeBSD right now. They aren't doing this for shits and giggles. I think it's fairly obvious they're trying to get C# running on other platforms.
 

survivor

Banned
C/C++ people, I need your help. Need to refresh my knowledge of the languages for the next two weeks.

1) Is The C Programming Language still the goto reference book for the language? I still have a copy from from school few years ago cause my database 2 prof recommended us to read it, but since we didn't use C for anything complex I just ended up skimming some pages. My understanding is C has couple of newer standards, but I'm not sure if they made radical changes.

2) Likewise anyone likes the C++ Programming Language book? I have one of the older editions of C++ Primer books from school, but it's a bit older so again I'm not sure if it's worth it to pick up one that covers the newer standards. Not to mention I never liked the Primer one so I wouldn't mind getting something else.
 

Kansoku

Member
So, I have to work on the traveling salesman problem using dynamic programing, but I'm having some difficulties modeling it.
I believe I need to calculate the distances from the adjacent vertices to the initial one (e.g. 2 to 1, 3 to 1 and 4 to 1), then calculate the distance from the other vertices to these "sets" (e.g. 2 to (3-1), 2 to (4-1), 3 to (2-1), 3 to (4-1)...), and so on, but I'm having trouble translating that into a data structure that I can go changing iteratively to get the answer (the shortest distance and the sequence that leads to it). I was thinking of using a matrix similar to how it's used on the matrix multiplication problem, but it didn't work out =/
Maybe a Hash Table/Map?

Can someone point me on right direction?
 

NotBacon

Member
So, I have to work on the traveling salesman problem using dynamic programing, but I'm having some difficulties modeling it.
I believe I need to calculate the distances from the adjacent vertices to the initial one (e.g. 2 to 1, 3 to 1 and 4 to 1), then calculate the distance from the other vertices to these "sets" (e.g. 2 to (3-1), 2 to (4-1), 3 to (2-1), 3 to (4-1)...), and so on, but I'm having trouble translating that into a data structure that I can go changing iteratively to get the answer (the shortest distance and the sequence that leads to it). I was thinking of using a matrix similar to how it's used on the matrix multiplication problem, but it didn't work out =/
Maybe a Hash Table/Map?

Can someone point me on right direction?

A matrix of structs maybe?
 

hateradio

The Most Dangerous Yes Man
"My code works and I don't know why"
This only happens when you don't have tests. (Which is always. ;p)

Those edge cases help weed out weird results.

I'm having some issues with Hibernate. I've got a User class that has, among other things, a List<User> as a list of friends. This is how I've got it set up:
Code:
    @Column(name = "user_id")
    @Id
    @GeneratedValue
    public long getId() {
        return id;
    }

    ...
I think I ran into a similar issue before. It was simply that I wasn't using the right self-referencing attributes or something.

This was a many-to-one relationship, but I had these annotations. You may have to follow something similar to form a parent/child-type of relationship using the @ManyToMany annotations and mappedBy entry.

Code:
@Entity
@Table(name = "objects")
public class O implements Serializable {

    // . . . id and stuff 

    // assign relations

    @ManyToOne(cascade = { CascadeType.ALL })
    @JoinColumn(name = "parent_id")
    private O parent;

    @OneToMany(mappedBy = "parent")
    private List<O> children;

}
 
Game changer: https://www.visualstudio.com/en-us/explore/cplusplus-mdd-vs

Visual Studio 2015 has the ability to write native C++ for Windows Mobile, Android and iOS. I wonder if their recent partnership with Chukong for Cocos 2D-X helped lead to this.

Whaaaa that's awesome! As someone who's not headed in the mobile app development direction, I like that Microsoft is coming to me.

So I have to write a GUI using Java for Windows by Tuesday and I have next to no experience with writing GUIs, writing for Windows, or using Java. I've got some docs for learning Java, but outside of the official documentation for Java and Windows do you guys have any advice/learning material?
 
Anyone got any experience with mobile development? Should i start with iOS or Android? If i satart with iOS I'll need to buy a MacBook Pro, which kinda sucks but it's not the end of the world.

I'm mostly interested in whichever has the lowest learning curve and is most likely to generate revenue. I'll probably release it as a free app with ads and an IAP to remove ads, so maybe they would be the same in terms of revenue, but I'm not sure.

Any links to good tutorials or books would be nice as well. Not looking for a total noob guide, as i have a lot of dev experience. Just not on mobile
 

Saprol

Member
Anyone got any experience with mobile development? Should i start with iOS or Android? If i satart with iOS I'll need to buy a MacBook Pro, which kinda sucks but it's not the end of the world.

I'm mostly interested in whichever has the lowest learning curve and is most likely to generate revenue. I'll probably release it as a free app with ads and an IAP to remove ads, so maybe they would be the same in terms of revenue, but I'm not sure.
61ecvHF.png


I think this info is based on 2013 sales. iOS users tend to spend more on apps but you're also looking at a higher entry cost with $99/year Apple dev licensing + whatever the cheapest Mac device you can get is vs a $25 one-time registration fee for Google Play. Unless maybe you want to try that Visual C++ for Mobile thing that just came out, then you can avoid buying a Mac for XCode.

I haven't tried doing mobile development. I'd probably only tinker on small useless apps for fun. Been using the same iPhone for a while and I've been unemployed so I didn't want to shell out a bunch of money just for that.
 

NotBacon

Member
So I have to write a GUI using Java for Windows by Tuesday and I have next to no experience with writing GUIs, writing for Windows, or using Java. I've got some docs for learning Java, but outside of the official documentation for Java and Windows do you guys have any advice/learning material?

Lol just dive head first into the syntax of Java. Shouldn't take long to get used to. Then read up on the wonderful world of Swing (it's not that wonderful). If you still need an IDE, I highly recommend IntelliJ.

Anyone got any experience with mobile development? Should i start with iOS or Android? If i satart with iOS I'll need to buy a MacBook Pro, which kinda sucks but it's not the end of the world.

I'm mostly interested in whichever has the lowest learning curve and is most likely to generate revenue. I'll probably release it as a free app with ads and an IAP to remove ads, so maybe they would be the same in terms of revenue, but I'm not sure.

Any links to good tutorials or books would be nice as well. Not looking for a total noob guide, as i have a lot of dev experience. Just not on mobile

Lower barrier of entry and easier learning curve? Android.
Most likely to generate revenue? iOS.

Can't recommend this book enough. Only I wouldn't recommend using Eclipse, i'd recommend Android Studio.
 
Lol just dive head first into the syntax of Java. Shouldn't take long to get used to. Then read up on the wonderful world of Swing (it's not that wonderful). If you still need an IDE, I highly recommend IntelliJ.



Lower barrier of entry and easier learning curve? Android.
Most likely to generate revenue? iOS.

Can't recommend this book enough. Only I wouldn't recommend using Eclipse, i'd recommend Android Studio.

If I end up doing Android I'll probably just use the Visual Studio 2015 android tools. I know iOS apps are more likely to generate revenue through the app store, but is the same true of ad revenue? (I don't know, actually asking). I mean are iOS users more likely to click ads in their app than Android users?

How hard is porting apps between iOS and Android? Obviously Objective C is out of the question if I want to port something, but is it hard to write iOS apps in C++?
 

WanderingWind

Mecklemore Is My Favorite Wrapper
So, I have a quick question I was hoping somebody could help out with. I made a sticky nav bar for single page that sits within a larger site. The nav bar has links like every other one you have seen

Home | One | Two | Three

<ul>
<li>Home</li>
<li> | </li>
<li>One</li>
<li> | </li>
<li>Two</li>
<li> | </li>
<li>Three</li>
</ul>

But because of how I have a hover state on the entire block that encompasses "Home" et al., the | also have a hover state. Is there a way to remove the styling around those? I've tried everything I can think of.
 
I have a question. I'm trying to find the largest value in an array using recursion, and not only do I return the largest value, but I have to return it's position. I was thinking of doing passing by reference. My problem is on writing the algorithm. I was thinking of using for loop to traverse the array to find the largest value, but I'm not sure because I've looked at other examples relating to recursion which deals with if else statements. In other words, base case and worst case. Within the for loop, I was thinking of doing if else statements which finds the max value and its position, else we call the function again to continue searching the largest value and it's position. Am I in the right direction? If not, what should I do? What algorithm should look at that deals with finding the largest value and its position recursively?
 

injurai

Banned
I have a question. I'm trying to find the largest value in an array using recursion, and not only do I return the largest value, but I have to return it's position. I was thinking of doing passing by reference. My problem is on writing the algorithm. I was thinking of using for loop to traverse the array to find the largest value, but I'm not sure because I've looked at other examples relating to recursion which deals with if else statements. In other words, base case and worst case. Within the for loop, I was thinking of doing if else statements which finds the max value and its position, else we call the function again to continue searching the largest value and it's position. Am I in the right direction? If not, what should I do? What algorithm should look at that deals with finding the largest value and its position recursively?

When dealing with an array in a manner where you are touch each element you should really just use iteration. Were you supposed to use recursion as part of an assignment? Because otherwise I would not take that approach to solving the problem. It's a lot of overhead and unnecessarily complicated for what you are doing.

You should create a variable called max_val. Compare each position of the array to max_val and if the array's value is larger set max_val to that. Then store that index of the array in another variable. Keep iterating through the array. Once your done, whatever is in those variables is your answer.
 
When dealing with an array in a manner where you are touch each element you should really just use iteration. Were you supposed to use recursion as part of an assignment? Because otherwise I would not take that approach to solving the problem. It's a lot of overhead and unnecessarily complicated for what you are doing.

You should create a variable called max_val. Compare each position of the array to max_val and if the array's value is larger set max_val to that. Then store that index of the array in another variable. Keep iterating through the array. Once your done, whatever is in those variables is your answer.

Yeah, I have to make a member function that recursively finds the largest number in the array. It's really annoying because I'm trying to figure out what would be the base case and worst case in terms of coding.
 

MiszMasz

Member
Yeah, I have to make a member function that recursively finds the largest number in the array. It's really annoying because I'm trying to figure out what would be the base case and worst case in terms of coding.

Do you mean best and worst case in terms of complexity, or the actual base and recursive cases for the function?
 
I have a question. I'm trying to find the largest value in an array using recursion, and not only do I return the largest value, but I have to return it's position. I was thinking of doing passing by reference. My problem is on writing the algorithm. I was thinking of using for loop to traverse the array to find the largest value, but I'm not sure because I've looked at other examples relating to recursion which deals with if else statements. In other words, base case and worst case. Within the for loop, I was thinking of doing if else statements which finds the max value and its position, else we call the function again to continue searching the largest value and it's position. Am I in the right direction? If not, what should I do? What algorithm should look at that deals with finding the largest value and its position recursively?

Have your function take 4 arguments. array, current position, total number of elements, and best value found so far. Base case is when current position = total number of elements.
 

injurai

Banned

So I'd make a void function. Pass it a reference to the array, the array size. Then pass it references to an higher scoped variable for max_val and index. In the method just have an if clause checking if your at the end of the array. If not recursively call the method again to check the array starting in the next position. Obviously be doing a comparison to find the max_val. Once you hit the bottom its done, and all those stack frames pop right off as you wind back up.
 
So, I have a quick question I was hoping somebody could help out with. I made a sticky nav bar for single page that sits within a larger site. The nav bar has links like every other one you have seen

Home | One | Two | Three

<ul>
<li>Home</li>
<li> | </li>
<li>One</li>
<li> | </li>
<li>Two</li>
<li> | </li>
<li>Three</li>
</ul>

But because of how I have a hover state on the entire block that encompasses "Home" et al., the | also have a hover state. Is there a way to remove the styling around those? I've tried everything I can think of.

Your hover state should be on the list elements, and then you can use the :nth-of-type(odd) pseudo selector

Code:
li:nth-of-type(odd):hover {
  color: red;      
}

But instead of having additional list elements with the pipes, you probably should do the dividers in CSS instead.

See examples of both:
http://jsfiddle.net/pgg6jqgb/2/
 
Hi GAF,

Have a C# assignment that is really sending me batty.

I've two classes, SystemDB and Connection.

SystemDB has a method, Register which takes an object instance of the Connection class and adds it to a list.

The part of the assignment that I'm getting stuck on, is that I've got to call that method and add to it, within the Connection constructor. I cannot change anything within the SystemDB class, and as stated it must occur within the Connection constructor.

So :

Code:
static class SystemDB
{

//some irrelevant code here

        #region Connection Data
        private static Dictionary<Customer, List<Connection>> _Connections = new Dictionary<Customer, List<Connection>>();
        public static ReadOnlyCollection<Connection> Connections
        {
            get
            {
                IEnumerable<Connection> result = _Connections.Values.SelectMany(list => list);
                return result.ToList<Connection>().AsReadOnly();
            }
        }

        public static void Register(Connection connection)
        {
            List<Connection> list = null;

            if (_Connections.ContainsKey(connection.Customer) == false)
                _Connections.Add(connection.Customer, list = new List<Connection>());
            else
                list = _Connections[connection.Customer];

            list.Add(connection);
        }
        #endregion

}

Code:
    class Connection
    {
        private Customer _Customer = null;
        private Device _Device = null;

       //some more irrelevant things here

        public Connection(Customer customer, Device device)
        {
               _Customer = customer;
               _Device = device; 
              SystemDB.Register(this)  //this doesn't work
              SystemDB.Register(new Connection(customer, device)) //stack overflow
        }

}

Any ideas? Or at least some guidance in right correct direction.
 
I wrote a toy JSON parser in Rust (around 400 lines without the tests) over the weekend:
https://github.com/GyrosOfWar/json-rs/

I chose to implement it as a hand-written recusive descent parser, I feel the code is fairly clean (not commented yet though).

It's not extensively tested and doesn't handle most corner cases but it could parse all of the JSON I threw at it so far. Also, the error handling is still pretty wonky and often doesn't give out the most recent/fitting error. Haven't really tested/compared the performance to other solutions either.

edit: Added comments.
 

TronLight

Everybody is Mikkelsexual
I'm working on a blackjack program in C, just because, and I'm stuck on strange bug.

This is the code (sorry for all the commented lines, I'm trying to track down this bug):


Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

#define NUM_SUITS 4
#define NUM_RANKS 13

void deal(int *pnum_cards, int *prank) {  

	static bool in_hand[NUM_SUITS][NUM_RANKS] = {false}; 
	const char rank_code[] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K',};        
//	const char suit_code[] = {'C','D','H','S'}; Non serve a nulla?
	int suit = 0, rank = 0;
//	printf("Qui arriva %d", *pnum_cards);	
	srand((unsigned) time(NULL)); 
	suit = rand() % NUM_SUITS;
        rank = rand() % NUM_RANKS;


		
	if (!in_hand[suit][rank]) {
		in_hand[suit][rank] = true;
		*pnum_cards = *pnum_cards - 1;
	printf("Pnum_cards In deal %d\n", *pnum_cards);
		if (suit == 0){
			printf("%c of Clubs \n", rank_code[rank]);
			}
		else if (suit == 1){
			printf("%c of Diamonds \n", rank_code[rank]);
		}
		else if (suit == 2){
			printf("%c of Hearts \n", rank_code[rank]);
		}
		else if (suit == 3){
			printf("%c of Spades \n", rank_code[rank]);
		}
	}
//	return rank;
//	printf("Rank In deal %d\n", rank);
	*prank = rank+1;
	printf("prank in deal %d\n", *prank);

}

void totrank_check(int *ptotrank, int *prank) {
//	*prank = *prank + 1;
	*ptotrank = *ptotrank + *prank;
////	printf("Total rank: %d\n", *prank);
//	if (*ptotrank > 21) {
//		printf ("You lose!\n");
//	}
//	else if (*ptotrank == 21) {
//		printf ("You win!\n");
//	}
	
}

int main() {

	int t, newcard;
//	int num_cards = 2, rank, totrank = 0, *prank, *ptotrank, *pnum_cards;
	int stay = {false};
	int f;
    	
	int rank = 0,  *prank = &rank;
	int totrank = 0, *ptotrank = &totrank;
	int num_cards = 2, *pnum_cards = &num_cards;
        printf("Prima del while %d\n", *pnum_cards);		
	
	printf("Your hand: ");

	while (*pnum_cards > 0) {
		deal(&num_cards, &rank);
//		printf("Nel while: %d\n", *pnum_cards);
//totrank_check(&totrank, &rank);
	}
   
	printf("\n");
		
//	while (*ptotrank < 24 && stay == false) {
//		printf("Another card? 1. Yes 0. No\n");
//		scanf("%d", &t);
//		newcard = t;
//
//		if(newcard) {
//			deal(&num_cards, &rank);
//			totrank_check(&totrank, &rank);
//		}
//
//		printf("Stay? 1. Yes 0. No\n");	
//		scanf("%d", &f);
//		stay = f;
//	}
	return 0;

}

Technically it works. The problem is, and I can't figure out why, that when it gets to
Code:
	printf("prank in deal %d\n", *prank);

Which is the last printf in function deal() it does something strange in the first while cycle, it prints that phrase like for a thousand times, then it suddenly stops, it exits the function, executes the second cycles, calls the function again, prints everything it has to, gets to the last printf, it prints it once and it stops, just as intended.

So I don't think it's a problem with the while-loop, because it basically works, it just gets stuck on that printf for a while. Any ideas?
 

Skittles

Member
I'm working on a blackjack program in C, just because, and I'm stuck on strange bug.

This is the code (sorry for all the commented lines, I'm trying to track down this bug):


Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

#define NUM_SUITS 4
#define NUM_RANKS 13

void deal(int *pnum_cards, int *prank) {  

	static bool in_hand[NUM_SUITS][NUM_RANKS] = {false}; 
	const char rank_code[] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K',};        
//	const char suit_code[] = {'C','D','H','S'}; Non serve a nulla?
	int suit = 0, rank = 0;
//	printf("Qui arriva %d", *pnum_cards);	
	srand((unsigned) time(NULL)); 
	suit = rand() % NUM_SUITS;
        rank = rand() % NUM_RANKS;


		
	if (!in_hand[suit][rank]) {
		in_hand[suit][rank] = true;
		*pnum_cards = *pnum_cards - 1;
	printf("Pnum_cards In deal %d\n", *pnum_cards);
		if (suit == 0){
			printf("%c of Clubs \n", rank_code[rank]);
			}
		else if (suit == 1){
			printf("%c of Diamonds \n", rank_code[rank]);
		}
		else if (suit == 2){
			printf("%c of Hearts \n", rank_code[rank]);
		}
		else if (suit == 3){
			printf("%c of Spades \n", rank_code[rank]);
		}
	}
//	return rank;
//	printf("Rank In deal %d\n", rank);
	*prank = rank+1;
	printf("prank in deal %d\n", *prank);

}

void totrank_check(int *ptotrank, int *prank) {
//	*prank = *prank + 1;
	*ptotrank = *ptotrank + *prank;
////	printf("Total rank: %d\n", *prank);
//	if (*ptotrank > 21) {
//		printf ("You lose!\n");
//	}
//	else if (*ptotrank == 21) {
//		printf ("You win!\n");
//	}
	
}

int main() {

	int t, newcard;
//	int num_cards = 2, rank, totrank = 0, *prank, *ptotrank, *pnum_cards;
	int stay = {false};
	int f;
    	
	int rank = 0,  *prank = &rank;
	int totrank = 0, *ptotrank = &totrank;
	int num_cards = 2, *pnum_cards = &num_cards;
        printf("Prima del while %d\n", *pnum_cards);		
	
	printf("Your hand: ");

	while (*pnum_cards > 0) {
		deal(&num_cards, &rank);
//		printf("Nel while: %d\n", *pnum_cards);
//totrank_check(&totrank, &rank);
	}
   
	printf("\n");
		
//	while (*ptotrank < 24 && stay == false) {
//		printf("Another card? 1. Yes 0. No\n");
//		scanf("%d", &t);
//		newcard = t;
//
//		if(newcard) {
//			deal(&num_cards, &rank);
//			totrank_check(&totrank, &rank);
//		}
//
//		printf("Stay? 1. Yes 0. No\n");	
//		scanf("%d", &f);
//		stay = f;
//	}
	return 0;

}

Technically it works. The problem is, and I can't figure out why, that when it gets to
Code:
	printf("prank in deal %d\n", *prank);

Which is the last printf in function deal() it does something strange in the first while cycle, it prints that phrase like for a thousand times, then it suddenly stops, it exits the function, executes the second cycles, calls the function again, prints everything it has to, gets to the last printf, it prints it once and it stops, just as intended.

So I don't think it's a problem with the while-loop, because it basically works, it just gets stuck on that printf for a while. Any ideas?
Not sure if related to your problem and my understanding of C compared to C++ is very basic. But for the "return rank" line in your deal function, that line is above code that still needs to execute. When it hits that return it will automatically exit that function and give that value to the program which requested it(unless this is different in C). On top of that, the function that has the "return rank" is a void function; which means it should not return a value anyway.
 

TronLight

Everybody is Mikkelsexual
Not sure if related to your problem and my understanding of C compared to C++ is very basic. But for the "return rank" line in your deal function, that line is above code that still needs to execute. When it hits that return it will automatically exit that function and give that value to the program which requested it(unless this is different in C). On top of that, the function that has the "return rank" is a void function; which means it should not return a value anyway.

I commentend return rank out because it was useless and forgot to remove it.
Anyway, the problem was that srand should be in the main and not in the function. Dunno exactly why though.
 

WanderingWind

Mecklemore Is My Favorite Wrapper
Your hover state should be on the list elements, and then you can use the :nth-of-type(odd) pseudo selector

Code:
li:nth-of-type(odd):hover {
  color: red;      
}

But instead of having additional list elements with the pipes, you probably should do the dividers in CSS instead.

See examples of both:
http://jsfiddle.net/pgg6jqgb/2/

Hey, I missed this response due to the jump in the page. Sorry for that and thanks for the pointers. I'll give it a shot when I'm in the office.
 

Sharp

Member
I wrote a toy JSON parser in Rust (around 400 lines without the tests) over the weekend:
https://github.com/GyrosOfWar/json-rs/

I chose to implement it as a hand-written recusive descent parser, I feel the code is fairly clean (not commented yet though).

It's not extensively tested and doesn't handle most corner cases but it could parse all of the JSON I threw at it so far. Also, the error handling is still pretty wonky and often doesn't give out the most recent/fitting error. Haven't really tested/compared the performance to other solutions either.

edit: Added comments.
Just FYI (not to discourage this) Rust already has a semi-official JSON library so you might want to use their JSON type even if you don't want their implementation of the parser.
 
Top Bottom