0

I have created two sorted arrays of size n and m with numeric value in a batch file.

FOR /L %%a IN (0,1,!n!) DO ECHO !vector[%%a]!
FOR /L %%a IN (0,1,!m!) DO ECHO !vector2[%%a]! 

This exactly shows the contents of my arrays.

Now I want to write a logic which will print merged sorted array.

SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
set i=0
set j=0
set /A totalElements =!n!+!m! 
FOR /L %%A IN (1,1,!totalElements!) DO (
    if !vector[!i!]! LSS !vector2[!j!]! (
        echo "First list"
        echo !%vector[!i!]%!
    ) else (
        echo "Second List"
        echo !%vector[!i!]%!
    )
)

So, this if else logic is not working. Any idea where in the syntax I have gone wrong? I guess I am not extracting the value from the array correctly?

aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • 1
    By `echo !%vector[!i!]%!` you mean something like `echo !vector[!i!]!`, right? Anyway, you cannot nest (delayed) variable expansion like this; in your first two lines of code you already see a work-around for how it works, using a `for` variable as the index, like `!vector[%%a]!`; you need to use a `for` variable also instead of `!i!` in `!vector[!i!]!` (for instance, `for /L %%a in (!i!,1,!i!) do (echo !vector[%%a]!)` would work, the loop iterates once only, with the value of `!i!`)... – aschipfl Oct 07 '16 at 08:08
  • Could it be that it tries to compare with a null value? For example: vector is 3 long and vector2 5. Note that the loop will go from 1 to 8 (which is to long for arrays of length 3 and 5). Further you do not increase the values of i and j or you left that out so it is hard to say where the error might be, if we do not know which elements are compared. Is there more code or an example you could provide (possible input, incorrect output, expected output)? – geisterfurz007 Oct 07 '16 at 08:10
  • 1
    @aschipfl: `for %%a in (!i!) do ...` - no `/L` needed. – Stephan Oct 07 '16 at 08:36
  • Sure, @Stephan, I chose `for /L` because it already appears in the code... – aschipfl Oct 07 '16 at 08:39
  • You can not use a _double_ delayed expansion like `!vector[!i!]!`. The problem with this notation and the way to solve it is fully described at [arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script](http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990). – Aacini Oct 07 '16 at 14:22

1 Answers1

1

Incomplete analyse:

  • where are defined n and m variables in set /A totalElements =!n!+!m! ?
  • in !vector[!i!]!, batch parser is looking for variables !vector[! and !]! instead of nesting like in !vector[%i%]!;
  • !%vector[!i!]%! is totally unclear for me.

Your question seems to be too broad (a bit unclear aim) to give more positive and constructive notes.

JosefZ
  • 28,460
  • 5
  • 44
  • 83