I want to convert this switch part of code in single line using ternary operators - switch-statement

for(int i=0; i<num.length; i++){
switch(num[i]/10){
case 10:
case 9:
aCount++;
break;
case 8:
bCount++;
break;
case 7:
cCount++;
break;
case 6:
dCount++;
break;
default: fCount++;
}
I want to short this code using multiple ternary operators in single line instead of switch statement. is it possible?

Not easily, no. First up, you haven't specified the language, it may be possible in C++ by using references, or in C by using pointers. But, even if it is possible, you'll most likely end up with truly ugly code.
If you're just looking to improve readability (the usual reason for shorter code, in my opinion), that can be done without changing the structure of the code, something like (assuming those are marks 0..100 and grades a..f):
for (int i = 0; i < num.length; i++) {
// Map <60 to f, 6x to d, 7x to c, 8x to b, 90+ to a.
switch (num[i] / 10) {
case 10: case 9: aCount++; break;
case 8: bCount++; break;
case 7: cCount++; break;
case 6: dCount++; break;
default: fCount++;
}
}

Related

Can I build on cases within a switch statement in Objective C?

I am somewhat new to programming in general. Even more so with Objective-C. I am trying to display labels and text boxes based on a value entered on a previous screen. Here is what I currently have:
switch (previousValue) {
case 1:
[label1 setHidden:FALSE];
[textField1 setHidden:FALSE];
break;
case 2:
[label1 setHidden:FALSE];
[textField1 setHidden:FALSE];
[label2 setHidden:FALSE];
[textField2 setHidden:FALSE];
break;
case n:
[label1 setHidden:FALSE];
[textField1 setHidden:FALSE];
[label2 setHidden:FALSE];
[textField2 setHidden:FALSE];
[labelN setHidden:FALSE];
[textFieldN setHidden:FALSE];
break;
}
Is there an easier way to do this? I have 60 possible cases. I am also using a switch statement in a similar fashion, but it deals with calculations that build upon each other. Any assistance would be greatly appreciated.
If they're IBOutlets you could set up IBOutletCollections which will create an array of the outlets you want to organize. Then you could simply call:
[_outlets setValue:#NO forKeyPath:#"hidden"];
it looks like you have N<=60 labels/textfileds and you set for each one hidden:False according to a value. Using a switch statement like that increases your code size and it's not very readable.
A better way is to use a bitFiled: each bit in the bitfield corresponds to one label/textfield - bit3 is used for label3/textField3.
Let's assume you only have 8 labels/textfields - you just need to choose a bigger data type for more bits - and see how you would code that:
char Bitfield;
int mask =0x01;
for( i=0;i<8;i++)
{
if (bitfield&mask)
{
setHidden(i); // sets the attributes for label/textfield i
}
mask>>=1;
}
Aside from the fact that the code becomes more readable, now you have control over each label/textfield individually - you can set the attributes only for label/textfields 1 and 5, if you wisht to.

OpenMP implement switch ... case

I'm trying to parallelize switch ... case (c++) using OpenMP directive, but despite my best efforts, the code goes slower than normal sequential execution.
I have used #pragma parallel, #pragma sections,
I have tried to rewrite the switch case with an if ... else statement
but with no good result ...
switch (number) {
case 1:
f1();
break;
case 2:
f2();
break;
case 3:
f3();
break;
case 4:
fn();
break;
}
Then there is a second problem, OpenMP won't break or return.
The switch cases cannot be implemented in Openmp, just by adding pragma's like parallel, section. The threads running along the parallel section divide work among themselves via the loop index or else they do the same work in a conditional loop. Openmp section needs to know either how many elements it needs to work on or a master condition which determines start and end. You want to make the input section as parallel instead of the functions (f1, f2, .. fn), so I am guessing you are processing a lot of "number". One way is to collect these numbers in a array/vector. Then, you can make a parallel for along this vector/array, calling the corresponding function.
while(some_condition_on_numbers)
{
// Collect Numbers in a vector / some array
}
#pragma omp parallel for
for(int counter = 0; counter < elements_to_process; counter++)
{
F(array_of_number[counter]);
}
F(int choice)
{
if(choice = 1) {f1(); }
if(choice = 2) {f2(); }
..
}

Convert if 'with range' to switch statement

Someone asked me today how to convert the following if statement to switch:
int i=5;
if(i>10)
{
Do Something;
}
else
{
Do Something else;
}
And I proposed that assuming i is an integer with only positive values:
int i=5;
switch(i)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10: Do Something else;
break;
case default: Do Something;
break;
}
Is there any other, more elegant way of doing it?
There is no direct way of doing that in C#, you can try the following.
int range = (number - 1) / 10;
switch(range)
{
case 0:
Console.WriteLine("1 to 10");
break;
case 1:
Console.WriteLine("11 to 20");
break;
//.,......
default:
break;
}
Not really sure how much clear it would be, IMO, the above approach would reduce the code readability, its better if you use if-else for the range checking. Also the above would work only if the range is constant.
First, note your two code examples (as were originally written) were not equivalent:
You're not Do[ing] Something Else when i==10 in your switch example.
But the original if code was checking on i>10 (as opposed to i>=10).
So case 10: should be explicitly included in your list of cases that fall through to Do Something Else.
To answer your question, I believe in some languages (eg pascal, objective C, I think?) a range similar to this is allowed:
switch(i)
{
case 1-10: // or is it "case 1 .. 10" ?
Do Something else;
break;
case default:
Do Something;
break;
}
But this is not supported in C#. Refer the very final point in the code discussion regarding "stacking" of case labels here MSDN switch(C#)

Switch fallthrough in Dart

I started learning Dart today, and I've come across something that my google skills are having trouble finding.
How do I have a fall-through in a non-empty case?
My use case is this: I'm writing a sprintf implementation (since dart doesn't have this too), which would work except for this fall-through thing. When parsing the variable type you can, for example, have "%x" versus "%X" where the upper case type tells the formatter that the output is supposed to be uppercase.
The semi-pseudocode looks like:
bool is_upper = false;
switch (getType()) {
case 'X':
is_upper = true;
case 'x':
return formatHex(is_upper);
}
The other ways I can think of doing this, would one of the following
1:
switch (getType()) {
case 'X': case 'x':
return formatHex('X' == getType());
}
2:
var type = getType();
if (type in ['x', 'X']) {
return formatHex('X' == getType());
}
Now, the second choice almost looks good, but then you have to remember that there are eleven cases, which would mean having eleven if (type in []), which is more typing that I'd like.
So, does dart have some // //$FALL-THROUGH$ that I don't know about?
Thanks.
The Dart specification gives a way for a switch case to continue to another switch case using "continue":
switch (x) {
case 42: print("hello");
continue world;
case 37: print("goodbye");
break;
world: // This is a label on the switch case.
case 87: print("world");
}
It works in the VM, but sadly the dart2js switch implementation doesn't yet support that feature.
From the dart language tour, your example of (2) should be correct.
var command = 'CLOSED';
switch (command) {
case 'CLOSED': // Empty case falls through.
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeClose();
break;
}
It would be an error if you tried to do something as follows
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break causes an exception to be thrown!!
case 'CLOSED':
executeClose();
break;
}
EDIT: This seems to only have worked due to a bug in the implementation of Dart. See the Dart 1.x language spec, section "17.15 Continue".
The bug is now fixed, as reported in a comment, so this no longer works. Keeping for historical reasons.
Also, a simplification of Lasse's answer is to use a simple continue; instead of continue <label>; as in:
bool is_upper = false;
switch (getType()) {
case 'X':
is_upper = true;
continue;
case 'x':
return formatHex(is_upper);
}
You can't have a non-empty case body in Dart that falls through, this will raise an error.
What I tend to do with anything other than very simple switch statements is to refactor all the common code out into functions, so that you don't have this multi-level control flow in the switch itself.
In other words, something like:
switch (getType()) {
case 'X':
return formatHex(true);
case 'x':
return formatHex(false);
}
There's no reason why you need to have fallthrough. It comes in handy when the actions in a case section can be carried out in toto at the end of another case section, but this method can do that without fallthrough and without making your switch statement complex.
It can also handle more complex cases where there are common actions that aren't included in toto at the end. For example, you may want to do something at the start or in the middle of the case section. Calling common functions handles that more than well enough:
switch (getType()) {
case 'X':
doSomethingOnlyForUpperCase();
doSomethingCommon();
doSomethingElseOnlyForUpperCase();
return formatHex(true);
case 'x':
doSomethingCommon();
return formatHex(false);
}
I actually also do this for languages (such as C) that support this sort of non-empty fall-through since I believe it aids in readability and maintainability.
Dart in 202207, just empty, instead of continue label
PermissionStatus recordStatus =
await Permission.requestSinglePermission(
PermissionName.Microphone);
switch (recordStatus) {
case PermissionStatus.allow:
case PermissionStatus.always:
case PermissionStatus.whenInUse:
return;
default:
break;
}

Technical name for switch statement without breaks

Does anyone know the "technical name" for a switch statement without breaks?
I have looked through several textbooks and searched online for quite a while with no results.
A switch statement with no breaks (and no loop, so it's not Duff's Device), I would just call a jump table.
Not one of the tools commonly used for structured programming, that's for sure.
When execution continues from one Case clause to the next it's called "fall-through".
switch (i) {
case 1:
// do something
case 2:
// do something else
break;
case 3:
// do another thing
}
Execution will "fall through" from case 1 to case, but not from case 2 to case 3. Is this what you're asking?
Fall through?
Or are you talking about a specific switch statement with no breaks, called Duff's Device?
send(to, from, count)
register short *to, *from;
register count;
{
register n=(count+7)/8;
switch(count%8){
case 0: do{ *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
}while(--n>0);
}
}

Resources