Open Side Menu Go to the Top
Register
Programming homework and newbie help thread Programming homework and newbie help thread

06-18-2016 , 10:35 AM
Quote:
Originally Posted by Craggoo
ternary to the rescue!

Code:
num < 0 ? num : num > 0 ? num * -1 : 0
Programming homework and newbie help thread Quote
06-18-2016 , 11:05 AM
I can read 1 ternary, but a stack of nested ternaries melt my poor brain
Programming homework and newbie help thread Quote
06-18-2016 , 12:49 PM
With good formatting, it's mo better

Code:
conditionalOperator = easyToRead ? singleLine.keep
                    : (thatBetter ? Return True : you.goFSelf);

Last edited by SiQ; 06-18-2016 at 12:59 PM.
Programming homework and newbie help thread Quote
06-19-2016 , 07:49 AM
Quote:
Originally Posted by Craggoo
expanding on previous post for a nested ternary... take this example...

Code:
if (x < 1) {
    if (x == 0) {
        return true
    }
} else if (x > 5) {
    if (x == 1) {
        return 1
    } else if (x == 2) {
        return 2
    } else {
        return false
    }
} else {
    return 'something else'
}
Assuming I made no mistakes, that above mess translated into a ternary looks like the following :

Code:
return x < 1 ? x == 0 ? true : void 0 : x > 5 ? x == 1 : 1 ? x == 2 ? 2 : false : 'something else'
Edit : to read nested ternarys is actually rather simple. If you have two consecutive expressions that end with a ? you are nesting the expression one level deeper. If you have two consecutive expressions that end with : you are breaking out of a nested ternary.
Quote:
Originally Posted by kazana
Yay, let's make it less readable!

Either it is num or it is the negative of num.

Imo, nesting ternaries is worse than having a chain of if/elseif/elseif/.../else. Grab a switch instead.
Quote:
Originally Posted by _dave_
I can read 1 ternary, but a stack of nested ternaries melt my poor brain
Let's run a complexity checker on the nested ternary vs, the if/else if approach. I'm almost certain that the if/ else if code will generate a high complexity number, not that sure that the nested ternary approach will generate a high complexity factor.
Programming homework and newbie help thread Quote
06-19-2016 , 03:48 PM
Code:
if (recordMatched == true) 
{
    recordsPerPageCount++;
    // Determines if number of records user wants to display has been reached.
    if (recordsPerPageCount == recordsPerPageRequested)
        {
	    cout << recordsPerPageCount << " records found this time through." << endl;
	    cout << "Enter x to break loop or any key to continue." << endl;

	    // Gives user option to stop searching
	    int ichar = _getch();
	    if (ichar == 'x' || ichar == 'X')
	        break;
         }
    // Resets boolean variable for later use
    recordMatched = false;
		}
I'm interested in finding a better / more succinct / clearer way to write the above code. What is happening there is I'm reading through a file of 1000 songs. That particular section of code keeps track of how many records have matched the user's search criteria, and lets the user break out of the search early should they choose.

I feel, especially after reading through a lot of posts in this forum, that I rely too strongly on if elif else statements, and it seems like people feel a different way is usually preferable, so I'm looking for some ways to incorporate that into programs I'm making for class.

I can post more parts of the program if need be, but it's fairly long. Also, my teacher had an example of the above code that I honestly feel is more confusing than mine, so I'm not totally unhappy with what I have. I just want to make sure I'm doing things correctly and as close to ideally as possible while I'm learning.

To be clear, some aspects of the program have to be in there. I have to allow the user to choose how many records per page between 1-100 and I have to allow the user the chance to break out.
Programming homework and newbie help thread Quote
06-19-2016 , 04:35 PM
Well, it's a little more verbose than is strictly required, but I think your example is fine. A slightly more succinct version would be

Code:
if (didMatch() && ++recordsPerPageCount == recordsPerPageRequest)  {
        // output/input/break here
}
Which is to say:
1. you don't have to do (foo == true) because the stuff in () is going to be evaluated as a bool
2. there's not actually much point in keeping the recordMatched in a variable, since you don't actually use it.
3. you don't need to increment the variable in a second line.
4. you don't need to have a nested if
Programming homework and newbie help thread Quote
06-19-2016 , 04:58 PM
Something feels slightly off about that if block and the way you manipulate the boolean gatekeeper (recordMatched).
Doing it in this way may or may not make sense depending on what happens to it in other parts of the loop.
Would be better to see it in context of the loop which it is embedded in.
Programming homework and newbie help thread Quote
06-19-2016 , 08:42 PM
Quote:
Originally Posted by LBloom
Code:
if (recordMatched == true) 
{
    recordsPerPageCount++;
    // Determines if number of records user wants to display has been reached.
    if (recordsPerPageCount == recordsPerPageRequested)
        {
	    cout << recordsPerPageCount << " records found this time through." << endl;
	    cout << "Enter x to break loop or any key to continue." << endl;

	    // Gives user option to stop searching
	    int ichar = _getch();
	    if (ichar == 'x' || ichar == 'X')
	        break;
         }
    // Resets boolean variable for later use
    recordMatched = false;
		}
I'm interested in finding a better / more succinct / clearer way to write the above code. What is happening there is I'm reading through a file of 1000 songs. That particular section of code keeps track of how many records have matched the user's search criteria, and lets the user break out of the search early should they choose.

I feel, especially after reading through a lot of posts in this forum, that I rely too strongly on if elif else statements, and it seems like people feel a different way is usually preferable, so I'm looking for some ways to incorporate that into programs I'm making for class.

I can post more parts of the program if need be, but it's fairly long. Also, my teacher had an example of the above code that I honestly feel is more confusing than mine, so I'm not totally unhappy with what I have. I just want to make sure I'm doing things correctly and as close to ideally as possible while I'm learning.

To be clear, some aspects of the program have to be in there. I have to allow the user to choose how many records per page between 1-100 and I have to allow the user the chance to break out.
Your instinct is correct. You have ifs, nested ifs, mutation, and data manipulations coupled with user interaction. None of these is needed.

It's also not clear to me why you need an option to break out if you are just parsing a text file of 1000 songs: that should be more or less instantaneous, why not just get all the results, and then show only part of them (if there are too many) by default, with the option to expand to "more results..." or something?

in any case, searching a file for results should just be applying filter() with your search term to an array or a stream. No ifs, no temporary variables, no counts, just an array of stream of results.... which you can display however you want.
Programming homework and newbie help thread Quote
06-19-2016 , 09:34 PM
map/reduce/filter in C++ (which is what this looks like) is... not well defined. You can do a lot of it with C++11 but it is not good. Functional programming in C++ is awkward to say the least.
Programming homework and newbie help thread Quote
06-19-2016 , 09:46 PM
Quote:
Originally Posted by RustyBrooks
map/reduce/filter in C++ (which is what this looks like) is... not well defined. You can do a lot of it with C++11 but it is not good. Functional programming in C++ is awkward to say the least.
ah, good point. i kind of glossed over the cout and thought it was js.
Programming homework and newbie help thread Quote
06-20-2016 , 09:47 AM
Quote:
Originally Posted by RustyBrooks
map/reduce/filter in C++ (which is what this looks like) is... not well defined. You can do a lot of it with C++11 but it is not good. Functional programming in C++ is awkward to say the least.
Can you explain what this means to me or point me to a link that will do so? Yes it is C++, sorry I always try to explicitly mention that at the top of my posts.

Also, recordMatched is used earlier and is, or something like it, (I think) necessary. The program does not just read through and display the contents of the CSV file; the user can also choose a song, launch Spotify, and play the song on the website. So that is part of the purpose of the break. Once you've found a song you want to play, you don't have to keep searching.
Programming homework and newbie help thread Quote
06-20-2016 , 10:40 AM
Quote:
Originally Posted by LBloom
Can you explain what this means to me or point me to a link that will do so? Yes it is C++, sorry I always try to explicitly mention that at the top of my posts.
It's kind of a long story. How much do you know about functional programming?

I'd have to see more of your program to be able to make any recommendations then, but the way you're treating recordMatched seems like a mistake to me.
Programming homework and newbie help thread Quote
06-20-2016 , 10:40 PM
Quote:
Originally Posted by kazana
Yay, let's make it less readable!

Either it is num or it is the negative of num.

Imo, nesting ternaries is worse than having a chain of if/elseif/elseif/.../else. Grab a switch instead.
Switch statements are far less versatile than if/else if/else chains && nested ternaries.
Programming homework and newbie help thread Quote
06-21-2016 , 06:58 PM
Quote:
Originally Posted by Craggoo
Switch statements are far less versatile than if/else if/else chains && nested ternaries.
Yes readable is subjective mostly.
Programming homework and newbie help thread Quote
06-21-2016 , 07:03 PM
Quote:
Originally Posted by LBloom
Code:
if (recordMatched == true) 
{
    recordsPerPageCount++;
    // Determines if number of records user wants to display has been reached.
    if (recordsPerPageCount == recordsPerPageRequested)
        {
	    cout << recordsPerPageCount << " records found this time through." << endl;
	    cout << "Enter x to break loop or any key to continue." << endl;

	    // Gives user option to stop searching
	    int ichar = _getch();
	    if (ichar == 'x' || ichar == 'X')
	        break;
         }
    // Resets boolean variable for later use
    recordMatched = false;
		}
I'm interested in finding a better / more succinct / clearer way to write the above code. What is happening there is I'm reading through a file of 1000 songs. That particular section of code keeps track of how many records have matched the user's search criteria, and lets the user break out of the search early should they choose.

I feel, especially after reading through a lot of posts in this forum, that I rely too strongly on if elif else statements, and it seems like people feel a different way is usually preferable, so I'm looking for some ways to incorporate that into programs I'm making for class.

I can post more parts of the program if need be, but it's fairly long. Also, my teacher had an example of the above code that I honestly feel is more confusing than mine, so I'm not totally unhappy with what I have. I just want to make sure I'm doing things correctly and as close to ideally as possible while I'm learning.

To be clear, some aspects of the program have to be in there. I have to allow the user to choose how many records per page between 1-100 and I have to allow the user the chance to break out.
Quote:
Originally Posted by gaming_mouse
Your instinct is correct. You have ifs, nested ifs, mutation, and data manipulations coupled with user interaction. None of these is needed.

It's also not clear to me why you need an option to break out if you are just parsing a text file of 1000 songs: that should be more or less instantaneous, why not just get all the results, and then show only part of them (if there are too many) by default, with the option to expand to "more results..." or something?

in any case, searching a file for results should just be applying filter() with your search term to an array or a stream. No ifs, no temporary variables, no counts, just an array of stream of results.... which you can display however you want.
Quote:
Originally Posted by RustyBrooks
map/reduce/filter in C++ (which is what this looks like) is... not well defined. You can do a lot of it with C++11 but it is not good. Functional programming in C++ is awkward to say the least.
Quote:
Originally Posted by gaming_mouse
ah, good point. i kind of glossed over the cout and thought it was js.
Maybe code this in a language that has decent support for map/reduce/filter. It will give you a different type of programming challenge.
Programming homework and newbie help thread Quote
06-21-2016 , 10:55 PM
Quote:
Originally Posted by adios
Yes readable is subjective mostly.
Versatile != readable
Programming homework and newbie help thread Quote
06-22-2016 , 12:02 AM
Quote:
Originally Posted by Craggoo
Switch statements are far less versatile than if/else if/else chains && nested ternaries.
Curious about that statement. Can you give me an example that could not be done with a switch statement?
Aesthetics aside, I cannot think of an if/elseif/.../else or ternary example that cannot be done with switches.
Programming homework and newbie help thread Quote
06-22-2016 , 12:38 AM
Quote:
Originally Posted by kazana
Curious about that statement. Can you give me an example that could not be done with a switch statement?
Aesthetics aside, I cannot think of an if/elseif/.../else or ternary example that cannot be done with switches.
any if / else if / else chain where the conditions for the different blocks are non-simple.

if you had something like

Code:
if (a == 5) {
 return 5
} else if (a == 6) {
 return 6
} else { 
 return
}
That can be easily represented with a switch

Changing the block conditions a little makes it pretty silly to represent with a switch. You could of course but its not pretty and not really what switches are meant for.

Code:
if (a == 5 && b == 10) {
 return 5
} else if (a == 6 && b == 15) {
 return 6
} else { 
 return
}
This is how you might represent the above with a switch.

Code:
switch (a) :{
  case 5 :
    return b == 10 ? 5 : void 0
  case 6 :
    return b == 15 ? 6 : void 0
  default :
    return
}
Ternary for that

Code:
return a == 5 && b == 10 ? 5 : a == 6 && b == 15 ? 6 : void 0
Basically, switches are only really meant for blocks with exceedingly simple conditions. You can of course figure out how to implement a switch for blocks with complex conditions but it doesn't really make sense to.

My rule of thumb generally is this :
1) Simple logic inside the blocks ? ternary
2) Simple conditions inside the block and non-simple logic inside the block ? if / else or switch (comes down to style)
3) Complex conditions inside the block and complex logic inside the block ? if / else

Last edited by Craggoo; 06-22-2016 at 12:44 AM.
Programming homework and newbie help thread Quote
06-22-2016 , 02:11 AM
You can use switch blocks to evaluate to true for the non-trivial if/else conditions above.

Code:
switch (true) {
  case (a == 5 && b == 10):
     return 5;
  case (a == 6 && b == 15):
     return 6;
  default:
     return;
}
Just as versatile for those cases unless I misunderstand the way switch evaluates its path.

Edit: Just to add, I agree with your rule of thumb. I just don't understand how switch is not as versatile, as in "cannot do the same thing".
Programming homework and newbie help thread Quote
06-22-2016 , 03:08 AM
Quote:
Originally Posted by kazana
You can use switch blocks to evaluate to true for the non-trivial if/else conditions above.

Code:
switch (true) {
  case (a == 5 && b == 10):
     return 5;
  case (a == 6 && b == 15):
     return 6;
  default:
     return;
}
Just as versatile for those cases unless I misunderstand the way switch evaluates its path.

Edit: Just to add, I agree with your rule of thumb. I just don't understand how switch is not as versatile, as in "cannot do the same thing".
Looks like that would work but not sure. Going to def check tomorrow. Never thought of a switch statement in that sense.
Programming homework and newbie help thread Quote
06-22-2016 , 05:55 AM
Quote:
Originally Posted by Craggoo
Versatile != readable
Yes basically. I would put it something like versatile code is not necessarily readable code. Efficient code is not necessarily maintainable code. Lots of coding goals can and often do conflict.
Programming homework and newbie help thread Quote
06-30-2016 , 06:06 PM
Just learning about structures in C++ and I want to make sure I'm getting it right. I'm making a program where I have to display a menu and fill orders for a restaurant (so sick of making those). Anyway, I create a structure called menuItem that has a string name and a double price. I then have to read data from a file to get the names and prices. I initially had something that looks like this:

Code:
//// Declares necessary menuItem variables
	//menuItem spamEggs;
	//menuItem eggBaconSpam;
	//menuItem eggBaconSausageSpam;
	//menuItem spam2SausageBacon;
	//menuItem spam4EggBacon;
	//menuItem spam4BaconSausageTomat;
	//menuItem spam4Eggs;
	//menuItem spam5Beans;
	//menuItem spam;
	//menuItem coffee;

	//// Assigns each menu item to an element of menuList
	//menuList[0] = spamEggs;
	//menuList[1] = eggBaconSpam;
	//menuList[2] = eggBaconSausageSpam;
	//menuList[3] = spam2SausageBacon;
	//menuList[4] = spam4EggBacon;
	//menuList[5] = spam4BaconSausageTomat;
	//menuList[6] = spam4Eggs;
	//menuList[7] = spam5Beans;
	//menuList[8] = spam;
	//menuList[9] = coffee;
	

	// Gets first the name and then the price of each menu item.
	for (int z = 0; z < MENU_SIZE; z++)
	{
		getline(dataFile, menuList[z].name, '%');
		dataFile >> menuList[z].price;
		dataFile.ignore(1, '\n');
	}
Basically, the two big sections where I listed a bunch of stuff and assigned values to the list indices (the parts I commented out) are completely unnecessary, right? All I need is the for loop unless I want to refer to the structures by something other than their list index, which I don't.
Programming homework and newbie help thread Quote
06-30-2016 , 06:46 PM
Some say that if/switch statements are an indicator of code smell and that they should be avoided altogether.
I am trying to use them as little as possible.
And nesting conditions, ternary or not, is definitely code smell.

Last edited by bex989; 06-30-2016 at 06:52 PM.
Programming homework and newbie help thread Quote
06-30-2016 , 09:20 PM
Sure, this is fine as long as you have
menuItem menuList[19]
above that
Programming homework and newbie help thread Quote
06-30-2016 , 10:45 PM
Quote:
Originally Posted by bex989
Some say that if/switch statements are an indicator of code smell and that they should be avoided altogether.
I am trying to use them as little as possible.
And nesting conditions, ternary or not, is definitely code smell.
This is something I struggle with as a beginning programmer. It is difficult to stop relying on the first tools you learned. In the same program as the above code, I have this:
Code:
for (int z = 0; z < MENU_SIZE; z++)
{
    if (orderList[z] > 0)
        subTotal += (orderList[z] * menuList[z].price;
}
The if statement here I now realize isn't even strictly necessary, so should I automatically get rid of it? Is there any value on skipping the math that will just equal 0?
Programming homework and newbie help thread Quote

      
m