LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   can I optimize this (http://www.linuxquestions.org/questions/programming-9/can-i-optimize-this-375546/)

kushalkoolwal 10-21-2005 04:31 PM

can I optimize this
 
hi,

I have writted this pretty self-explanatory function. Is there any better way to implement this using while or for loop?

Code:

device_boot()
{
if [[ $IDE == "/dev/hda" ]]
then
BOOTABLE_DEVICE="hd0"
fi

if [[ $IDE == "/dev/hdb" ]]
then
BOOTABLE_DEVICE="hd1"
fi

if [[ $IDE == "/dev/hdc" ]]
then
BOOTABLE_DEVICE="hd2"
fi

if [[ $IDE == "/dev/hdd" ]]
then
BOOTABLE_DEVICE="hd3"
fi
echo "The bootable device is $BOOTABLE_DEVICE"
}


aldimeneira 10-21-2005 05:17 PM

I understand the function however I'm not familiar with that specific programming language (I supose it's C/C++).

Why not use a switch,

"/dev/hda" can be a String in Java:

String hd = ( the value of $IDE in a series of characters )

I don't know how to implement this in the language you're using (...maybe a vector of characters):

- changing the String
/dev/hdb
- to a character
b

So you can change it to:

char hd = 'b'

switch{
case: hd = a
BOOTABLE_DEVICE="hd0"

break;
case: hd = b
BOOTABLE_DEVICE="hd1"
break;

case: hd = c
BOOTABLE_DEVICE="hd2"
break;

case: hd = d
BOOTABLE_DEVICE="hd3"
break;

default:

break;
}

This is what I remember about the "switch" syntaxis, it may be different and I've no idea how it will look in your final function.

kushalkoolwal 10-21-2005 05:32 PM

This is basic shell scripting. Well using case statement won;t help reducing number of lines of code. By optimization I mean can I reduce the number of lines of code by putting it some for or while loop.

thanks

vladmihaisima 10-21-2005 07:22 PM

You can do it with one line of code :D :

Code:

BOOTABLE_DEVICE=hd$(echo $IDE | cut -f 3 -d d | tr 'abcd' '0123')
Of course I wouldn't recommend such a thing (it's not extensibile and not easy to understantd). Your first implementation seems resonable.

kushalkoolwal 10-21-2005 07:25 PM

Quote:

Originally posted by vladmihaisima
You can do it with one line of code :D :

Code:

BOOTABLE_DEVICE=hd$(echo $IDE | cut -f 3 -d d | tr 'abcd' '0123')
Of course I wouldn't recommend such a thing (it's not extensibile and not easy to understantd). Your first implementation seems resonable.


yeah I was looking something similar to that. Wil try that....

rsheridan6 10-21-2005 09:05 PM

This seems to scream out for a case command, which would not as short as the cryptic pipe thing posted above, but would be both shorter and more readable than what you have. For examples, if your profile is correct and you run debian, look in /etc/init.d . Most scripts in there that control daemons use the case command.


All times are GMT -5. The time now is 03:50 PM.