this procedure takes a generic_sequence and randomly generates a new one
even if from the echo I can see tempSeq is correct the final return value has only one item in it I guess before returning the function runs one last time and corrupts the data How can I avoid this and get a clean straight return ?
proc randomseq(passSeq1: seq[int], tempSeq1: seq[int] = @[]): seq[int] =
var
passSeq : seq[int]
tempSeq : seq[int]
len_seq : int
ran : int
passSeq = passSeq1
tempSeq = tempSeq1
len_seq = (len passSeq)
ran = rand_num(1, len_seq)
tempSeq.add passSeq[ran-1]
passSeq.delete (ran-1)
if (len_seq > 1):
discard randomseq (passSeq, tempSeq)
else:
echo "--------tempSeq: " , tempSeq
return tempSeq
return tempSeq
newtesting = randomseq mysequence
Do you really think that this "seq[int] = @[]" in the procedure header is a good idea?
I don't know, maybe that is ok, but I have not really an idea where that seq is allocated for this case. I would try to allocate it in the proc body.
[Addition]
And of course you may consider making your temp seq a var parameter!
thank you ! Now it works. I need to pass two seq each time because I am picking a random index from the 1st to generate the 2nd one. I initialize it the 2nd seq argument in the beginning because on the 1st call there is only the main seq (the random has not being generated yet)
proc randomseq(passSeq1: seq[int], tempSeq1: seq[int] = @[]): seq[int] =
var
passSeq : seq[int]
tempSeq : seq[int]
len_seq : int
ran : int
passSeq = passSeq1
tempSeq = tempSeq1
len_seq = (len passSeq)
if (len_seq < 1):
return tempSeq
else:
ran = rand_num(1, len_seq)
tempSeq.add passSeq[ran-1]
passSeq.delete (ran-1)
tempSeq = randomseq (passSeq, tempSeq)
return tempSeq
newtesting = randomseq mysequence