[Solved]Bash:Subtract a set of numbers from each other in pairs?

Solution: see my reply.
I know the description isn't exact, there really isn't an easy way to describe it with the limits of the title so the circumstances are these:
say I have arrays which contain small numbers like so:
ex. 12, 7 and 13
I which is greater than the other when comparing the following number in sequence and need to subtract the lower one from it. the 3 numbers above in that order will end up producing two simple problems:
(12 - 7) and (13 - 7). The results will be stored in an array in the order they were performed (left to right)
Currently I'm trying to accomplish this with a while loop and some if statements
Note: the array "Tree" is named such so I can print the results somewhat like so after performing this operation until only one result is left:
12   7   13
     5   6
        1
#!/usr/bin/env bash
Num_Set=( 12 7 13 )
A=0 ; B=1
while (( ${#Num_Set[B]} >= 1 )) ; do
if (( ${Num_Set[A]} >= ${Num_Set[B]} )) ; then
Tree[A]=$(( ${Num_Set[A]} - ${Num_Set[B]} ))
elif (( ${Num_Set[A]} < ${Num_Set[B]} )) ; then
Tree[A]=$(( ${Num_Set[B]} - ${Num_Set[A]} ))
fi
A=$(( A++ )) ; B=$(( B++ ))
done
echo "${Num_Set[@]}"
echo "${Tree[@]}"
I believe i'm on the right track but this becomes an endless loop for reasons unknown for to me.
Any bash hackers out there know whats happening here?
Last edited by Thme (2013-06-12 18:57:40)

And bash has associative arrays as well. Your claim that the $ is not recommended is not valid at all:
declare -A aa
aa[bb]=100
aa[0]=1
bb=0
echo $(( aa[bb] + 1 ))
101
echo $(( aa[$bb] + 1 ))
2
My apologies however I tested my original post with http://www.shellcheck.net/ upon finding the site through an unrelated thread. This was an example test to illustrate what was commented on and what was not. This works in the shell:
A=( 2 1 10 )
B=2
echo $(( A[0] + A[B] - ${A[${A[$B]}]} - A[$B] + ${A[A[1]]} + A[0] - ${#A[2]} ))
23
However ${A[${A[$B]}]} and ${A[A[1]]} were commented on by shellcheck with "don't use $ on variables in (( ))". Aside from that it does still work. Also I tested this as well:
echo $(( A[${A[0]}] + 1 ))
And although it works in my bash it gets "This $((..)) expression is malformed." and "Unexpected "}". Fix any mentioned problems and try again." when tested in shellcheck. I suspect that maybe a fault on shellcheck but either way it looks less readable than just A[A[0]]. So what I've gathered from all this is that, although the above examples all work, the following ones below are probably the best practice here for use in (( )).
#!/usr/bin/env bash
declare -A AA
AA[BB]=3
AA[0]=1
BB=0
A=( 2 1 10 )
B=1
echo $(( A[0] + 1 ))
echo $(( B + 1 ))
echo $(( A[0] + 1 ))
echo $(( A[B] + 1 ))
echo $(( A[A[0]] + 1 ))
echo $(( ${#A[2]} + 1 ))
echo $(( ${A[2]/0/1} + 1 ))
echo $(( A[BB] + 1 ))
echo $(( AA[$BB] + 1 ))
echo $(( AA[BB]++ ))
So in the cases of using arrays in manners like ${#A[2]}, ${A[2]/0/1} and AA[$BB] ( AA[BB] being different. ) using $ would be necessary inside of (( )). If I missed any or there are any needed corrections please note them as I'm concerned with good practices here. I'll leave it at that. Again thanks for the help everyone.
Last edited by Thme (2013-06-15 00:49:54)

Similar Messages

  • Can the 12 Ports of the PCI 6508 set independen​t from each other to I and O?

    Hello,
    can the 12 Ports of the PCI 6508 set independent from each other to I and O?
    Or are they configured in groups like A, B and C ports?
    Thanks,
    BFutzi

    The attached example demonstrates how to write a digital pattern to multiple ports with a single write call, overcoming the 32-line limitation of the DIO Port Write VI.
    Attachments:
    Write_to_Multiple_Ports_(6507-6508).vi ‏49 KB

  • Can the 12 Ports of the PCI 6508 set independent from each other to I and O?

    Hello,
    can the 12 Ports of the PCI 6508 set independent from each other to I and O?
    Or are they configured in groups like A, B and C ports?
    Thanks,
    BFutzi

    Hello,
    I am upgrading from Traditional DAQ to DAQmx on an old installation with a PXI-6508 board.
    I struggle with this reset problem.
    I read the post from NI "Archived: PCI DIO-96/PXI 6508/PCI 6503 Digital Ports cannot be Controlled Independently".
    This post states:
    "NI-DAQmx is expected to work around this issue by resetting the other ports of the 8255 to the last known state.This means that the other ports may momentarily be reset, but will return to their previously set values."
    Does anyone can confirm that this is true?
    I notice that e.a. port 11 is reset when I write to port 10, but the values of port 11 are not set to the last value I had written to it.
    Herwig.
     

  • How can i design square signal which having a positive and negative values equal to each other and separated from each other by controlled time or distance

    How can i design square signal which having a positive and negative values equal to each other and separated from each other by controlled time or distance, As it is shown in the figure below. and enter this signal in a daq.
    Solved!
    Go to Solution.

    By the time you spend for the nice diadram you might have done the vi
    Your DAQ like to have a waveform (array of values and dt ak 1/samplerate)
    If you set the samplerate you know the array length , create a array of zeros, and set the values of both amplitudes ... 
    Since I don't want to wire others homework here are some pictures
    And there are some drawbacks is room for improvement in my solution, just think of rounding errors ... and what might happen if the arrays get bigger ....
    Spoiler (Highlight to read)
    Greetings from Germany
    Henrik
    LV since v3.1
    “ground” is a convenient fantasy
    '˙˙˙˙uıɐƃɐ lɐıp puɐ °06 ǝuoɥd ɹnoʎ uɹnʇ ǝsɐǝld 'ʎɹɐuıƃɐɯı sı pǝlɐıp ǝʌɐɥ noʎ ɹǝqɯnu ǝɥʇ'

  • How to hide different Viual Studio Projects from each other in one TFS Team Project with areas?

    Hi,
    at the moment I try to set up a "good" architecture for projects in TFS for our company.
    As often mentioned in TFS documentation we try to reduce the number of Team projects in our company which is organized in different business units (BUs).
    One great Team project shall contain a number of different Visual Studio projects, each one belonging to a separate BU.
    The grouping is as follows:
    Global Team project
           Business Unit A
                         Visual Studio Project A1
                         Visual Studio Project A2
           Business Unit B
                         Visual Studio Project B1
                         Visual Studio Project B2
    The programmers in business unit A must not see the Visual Studio projects of Business Unit B, but both groups (A an B) use the same process model (that is the reason why we try to group them in on team project).
    I try to put all the projects from both BUs in one TFS team project and separate them logically by an Area hierarchy like mentioned above.
    But areas only separate work items from each other, not Visual Studio projects.
    In Source Control Explorer I can only assign security issues on team project level (Global Team Project), not on business unit level.
    So every developer in BU A can see the Visual Studio projects in BU B...
    How can I model these dependencies?
    Regards and thanks
    Lothar

    Hi Lothar, 
    Thanks for your post.
    What’s the version of your TFS and VS?
    In Source Control Explorer, you can right-click on Business Unit A folder and select
    Advanced>>Security… to deny other group(s)’ access permissions on this folder. Then use the same way to set permissions on Business Unit B folder too.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • I gave my Mom new iPad - she's forgotten her pass code. She has now been locked out and told her "iPhone is disabled". How do I help her? We are 2 provinces away from each other!

    I gave my Mom an iPad. She has created an Apple ID (twice) and forgotten her pass code. She has now been locked out and told her "iPhone is disabled". How do I help her? We are 2 provinces away from each other!
    She is 75 and frustrated!  How do I walk her through this?
    Diane

    Locked Out, Forgot Lock or Restrictions Passcode, or Need to Restore Your Device: Several Alternative Solutions
    1. iOS- Forgotten passcode or device disabled after entering wrong passcode
    2. iPhone, iPad, iPod touch: Wrong passcode results in red disabled screen
    3. Restoring iPod touch after forgotten passcode
    4. What to Do If You've Forgotten Your iPhone's Passcode
    5. iOS- Understanding passcodes
    6. iTunes 10 for Mac- Update and restore software on iPod, iPhone, or iPad
    7. iOS - Unable to update or restore
    Forgotten Restrictions Passcode Help
                iPad,iPod,iPod Touch Recovery Mode
    You will need to restore your device as New to remove a Restrictions passcode. Go through the normal process to restore your device, but when you see the options to restore as New or from a backup, be sure to choose New.
    You can restore from a backup if you have one from BEFORE you set the restrictions passcode.
    Also, see iTunes- Restoring iOS software.

  • When my husband and I try to share our libraries and import from each others libraries, we get as far as seeing the library on the screen. The next step is to look for the 'Show' menu at the bottom of the screen, but neither of us has any such thing. ?

    When my husband and I try to import from each other's libraries, using Home Sharing, we are intructed to look for the "Show" menu at the bottom of the screen. Neither of us has anything like this on our screens. How and where do we locate it? We both have the latest itunes running.

    Hey fantail163,
    If you are not seeing the button to show menu, try out the troubleshooting steps for Home Sharing.
    Troubleshooting Home Sharing
    http://support.apple.com/kb/ts2972
    Thanks for using Apple Support Communities.
    Regards,
    -Norm G.

  • Question about garageband: I have 3 short original songs that i wanted to merge ala "Bohemian Rhapsody". Is that possible in garageband? their tempos are all different from each other. Advance thanks.

    Question about garageband: I have 3 short original songs that i wanted to merge ala "Bohemian Rhapsody". Is that possible in garageband? their tempos are all different from each other. Advance thanks.

    First of all, GarageBand iOS allows for only one tempo and there is no Merge Song feature.
    What you can do.
    Switch between the songs and copy-paste the individual Tracks. You can also Merge Tracks if you run into the 8 Track limitation.
    Hope that helps
    Edgar Rothermich
    http://DingDingMusic.com/Manuals
    'I may receive some form of compensation, financial or otherwise, from my recommendation or link.'

  • Isolating guest VMs from each other (not just the host)

    Hello Everyone,
    I've been playing around with visualization for a long time, but largely for testing and educational purposes.
    For the first time I'm thinking of actually running some production systems in virtual machines instead of on physical hardware which which raises some new concerns for me that weren't really relevant previously, namely, security.  In particular, I've been thinking about how to isolate the guest VM processes from each other.
    It's decades-old best practice to isolate different server services to different machines to help prevent, say, security problems with your web server also comprising your mysql server.  When you start virtualizing your infrastructure, you lose this benefit to a degree, if someone manages to compromise one of your VM servers and manages to exploit a vulnerability in your hypervisor to gain access to the host, it's no big leap to assume that they may be able to get access to your other virtual machines running on that host.
    It seems to me, that if you want to improve your resilience to this kind-of exploit that you want to increase the isolation of your VM processes from each other.  You could, say, run them as different users.  If you're careful about permissions, then you gain back some of the security of running your servers on seperate physical hardware.  An attacker could still exploit a local privilege escalation bug, but it at least provides another line of defense.
    This sort of thing seems to be possible with qemu virtual machines, though it does require some work to get anything besides user mode networking working. 
    On the other hand, this sort of thing seems to be largely impossible with libvirt.  It's possible to run as qemu vms as different users using 'qemu://session' but the documentation seems to suggest that this limits you to using the qemu user mode networking, which isn't practical for running publicly accessible servers.  Since, as far as I can tell, all of the visualization management products around are based off of libvirt, this surprises me.  It seems to me that someone would have wanted to try and do something like this before, but nobody has (as far as I can tell).
    Indeed, there seems to be very little documentation out there about using qemu with tun/tap networking when running as non-root user.  There is some documentation out there about using VDE (mostly via the deprecated vdeq wrapper), but alot of qemu write-ups skip over it.  There's enough out there to suggest it's possible, it just doesn't seem to be written up anywhere (yet, maybe I'll write it up myself someday).
    So, this makes me wonder, 'why not?'.  Are there other things people are doing to isolate guest VMs from each other?
    What are people running production services in VMs doing?

    I suppose this is also something to think about, but I don't think I'd be that worried about it for my use-case.  The majority of systems I plan to run could run completely headless and the physical security for the host computers should be pretty good.  I'm more concerned remote code exploits in one particular VM allowing an attacker to execute on the host or in other guest VMs.

  • Distribution channels deviate from each other.70 /or 10 (reference), Message no. V2011

    I have a problem when create the "Credit memo request" doc. type CR, reference doc. is billing doc. and my sales doc. that i did the billing doc. sales area is 2100/10/71 and i have to create cr doc with reference to billing doc. and sales area should be 2100/70/99 but while i creating cr doc. with reference to billing doc. system gives error distribution channel deviate from each other 70./or 10 (reference).
    I have seen the early post but there where no proper solution on it.
    please provide me solution i have to create cr doc. with reference to billing doc. and simply meaning with different distribution channel and division from preceding doc.
    Thanks
    Regards,
    Abhijeet

    Hi man,
    The thing is that the credit memo with reference is precisely affect the balance of the Customer - Sales Area, imagine a Report by Sales Area saying the total Sales Amount of the Sales Area is 1 million, but then you turn to another sales area and discover that the same customers have credit notes for 1.5 million, insane. The purpose of referencing the credit/debit memos is that, not to lose track, including Sales Areas. Otherwise make no sense to create it with reference, just create a Credit Memo with the customer you want to affect in the sales area you want to affect, no reference. For audit purposes justify the document based on REASON FIELDS and approvals, let me explain this a little more:
    One single person CANNOT create Credit Memos, cos this could lead to wrong ethical behavior, to avoid this some companies recommend to have more than one person involved in the process of Credit notes creation, what I've done on this situation is: provide access to one person to CREATE Credit/Debit memos using the standard transaction VA01, in the settings of the Sales Order Type I customize that the document will be created automatically blocked for billing (can use a UserExt to always have this field populated on the creation). This person WONT have access to modify Credit/Debit notes (VA02) but his supervisor will and this supervisor is responsible to approve and modify the blocking field to release the doc for billing. Yes, he can also change the amount but you will already have the log of changes in place for audit purposes.
    This is more than a technical issue, a process issue. My kind suggestion is to challenge the business and get clearly why they want to have a referenced Credit Memo without using the Sales Area of the based Billing Doc.
    Hope it helps...
    Saludos!
    Ricardo

  • I have 2 different MacBooks (owned by 2 people) connected to my Time Capsule. I want to use the Time Capsule to back up both MacBooks separately from each other. Can one person access the hard drive of the other person, on the same Time Capsule?

    I have 2 different MacBooks (owned by 2 people) connected to the same Time Capsule over a wifi network. I want to use the Time Capsule to back up both MacBooks separately from each other. Can one person access the hard drive of the other person, on the same Time Capsule? Is there a way to ensure that the files on the 2 laptops are kept private from each other? Thanks!

    If someone really wants to do something, it won't take them long to find out how to do it. 
    http://pondini.org/TM/17.html
    Security on a Time Capsule is a bit like installing a lock on a tent. It will keep the honest folks out, but probably not the others.

  • We have 2 email accounts on our Ipad and want to password protect them from each other?

    We have 2 email accounts on our Ipad and want ro password protect them from each other.I cannot see how tomdo this.

    The only way to get around this would be if you could access each of those e-mail accounts via web mail. You can put a shortcut on the screen and then enter the login info for each one. Everything would be viewed on a web basis and nothing should be downloaded to the ipad itself. (beyond being in safari's history)

  • Is Two Classes that call methods from each other possible?

    I have a class lets call it
    gui and it has a method called addMessage that appends a string onto a text field
    i also have a method called JNIinterface that has a method called
    sendAlong Takes a string and sends it along which does alot of stuff
    K the gui also has a text field and when a button is pushed it needs to call sendAlong
    the JNIinterface randomly recieves messages and when it does it has to call AddMessage so they can be displayed
    any way to do this??

    Is Two Classes that call methods from each other possible?Do you mean like this?
       class A
         static void doB() { B.fromA(); }
         static void fromB() {}
       class B
         static void doA() { A.fromB(); }
         static void fromA() {}
    .I doubt there is anyway to do exactly that. You can use an interface however.
       Interface IB
         void fromA();
       class A
         IB b;
         A(IB instance) {b = instance;}
         void doB() { b.fromA(); }
         void fromB() {}
       class B implements IB
         static void doA() { A.fromB(); }
         void fromA() {}
    .Note that you might want to re-examine your design if you have circular references. There is probably something wrong with it.

  • Identifying install disc 2's from each other?

    I have a 2007 mac mini with a set of restore discs... I also think I'm holding on to my parents imac restore discs or they are just an extra set Apple sent me a while back when I was having trouble with my 2007 imac.
    so one of the disc 1s - says "For Mac Mini" the other disc 1 says, "For Mac Computers"
    but the real confusion is which disc 2 goes with which?
    both are 2007 Mac OS X Install Disc 2
    only difference is in the set of numbers...
    2Z691-6147-A
    and
    2Z691-6157-A
    anyone have any idea how to pair them up without doing a an actual restore? thanks.

    i'm trying to avoid a restore.
    I wasn't suggesting a Restore I don't think, Just seeing which Mac booted from which install Disc... & maybe failed at some point before actually doing a Restore.
    if they aren't in your "vast collection" why do you need to know?
    So I might be able to help others that ask in the future... my only purpose hear is to try to help.

  • After installing ios 6 to my iphone4 and my daughters iphone4s we now get each others text messages. How can we disconnect from each other so that I don't receive the text messages from her and her friends and she does not receive mine?

    After installing IOS6 on my iphone 4 and my daughters iphone 4s we have this wonderful connection that we would like to break.  We are now seeing/receiving each others text messages.  I love my daughter but I don't really want to get all of her text messages from her friends and I don't really want to read every response she sends.  Additionally, she can also see my text messages and there are times I really don't need for her to know everything that I am doing. 
    So It is time to cut the cord we need our own seperate texting.  I am not sure what we did to have this happen but how do we undo it?

    Get your Apple ID sort out.
    Only use the same Apple ID in Settings > iTunes & App Stores to share purchases, no where else.
    Here some tips, it was written for IOS 5 but it's still valid for iOS 6.
    iOS 5 & iCloud Tips: Sharing an Apple ID With Your Family

Maybe you are looking for

  • How can I mix a whole show?

    I am using Logic Pro.  I am new to the software.  I have recorded a live show.  I want to mix all of the songs as the show.  However, I want them to bounce into individual song files so I don't end up with one big file.  I can force it by moving the

  • Blinking amber in time capsule

    Hi, i am experiencing some trouble while configuring my time capsule for the 1st time.. the airport utility software locates the device but when i try to configure, it errors out with error code -4. i also tried to reset it but no luck. strange thing

  • Convert editable PDF to read-only when sent in an email - JavaScript

    I have a real estate company that is trying to have an application that a agent and customer can fill in the needed information, hit a submit button, have the javascript compose an email with the attached pdf.  Here's the issue I'm having: I need to

  • Previously viewed items in a web search are no long highlighted

    When I do a google search, or search of any kind, previously viewed items are no longer highlighted. I have no way of knowing which items I have already viewed. == This happened == Every time Firefox opened == July 8, 2010

  • Parameters in XMLQuery

    Sorry to repost this question but haven't had any reply to the previous post. The question: is how to pass the "EMAIL" in the query below as parameter (instead of hardcoding it). SQL> select acc_no, XMLQuery( 'for $i in /CommRecord where $i/CommType