Solved Help with awk loop

Lenovo / C200
February 19, 2012 at 04:07:28
Specs: Windows XP PRO SP3, 1,60 GHz/1,49 GB
Hello everyone,
I have an awk script "lotto.awk" and it can generate only a single line (awk -f lotto.awk). However, I would like to generate 100 lines.
Can anyone help me to remake the specified script so that it can generate multiple lines at one execution of script.
Here is the script:
#-----
BEGIN {
srand()
for (j=1; j<=7; ++j) {
do {
select=1+int(rand()*39)
} while (select in pick)
pick[select] = select
}
for (j in pick)
printf("%s ", pick[j])
printf("\n")
}
#-----

Thanks in advance.
imrsi25


See More: Help with awk loop

Report •


#1
February 19, 2012 at 14:38:29
✔ Best Answer
This is one way to do it. Add a variable for the number of times to loop, 5 in this case:

awk -f lotto.awk -v cnt=5

Keep this in mind:
1) If cnt is not defined, default to 1.
2) Add a for loop to call the rand() function from 1 to cnt times
3) delete the array element each time it is printed or new elements are just added to the array.

# lotto.awk (modified)
BEGIN {
# if cnt variable is not defined, set to 1
if(cnt == "")
   cnt=1

srand()
for (k=1; k<=cnt; k++)
   {
   for (j=1; j<=7; ++j) {
   do {
      select=1+int(rand()*39)
      }
      while (select in pick)
         pick[select] = select
      }
   for (j in pick)
      {
      printf("%s ", pick[j])
      # delete array element so it's not used on next loop
      delete pick[j]
      }
   printf("\n")
   }
}
#-----

Let me know if you have any questions.


Report •

#2
February 19, 2012 at 18:17:44
Dear friend,
Yes, that's what I was looking for.
Thank you very much for your help.
If not too much, can you help me how to remove
trailing space from the last line item.
Once again, thank you.
Regards,
imrsi25

Report •

#3
February 19, 2012 at 21:52:57
You're welcome.

Do you mean something like this:

#-----
# lotto.awk (modified)
BEGIN {
# if cnt variable is not defined, set to 1
if(cnt == "")
   cnt=1

srand()
for (k=1; k<=cnt; k++)
   {
   for (j=1; j<=7; ++j) {
   do {
      select=1+int(rand()*39)
      }
      while (select in pick)
         pick[select] = select
      }
   wt=1
   for (j in pick)
      {
      # at the last line (k=cnt) and the last element (wt=7)
      # do not print a space
      if(wt == 7 && k == cnt)
         printf("%s", pick[j])
      else
         printf("%s ", pick[j])
      wt++
      # delete array element so it's not used on next loop
      delete pick[j]
      }
   printf("\n")
   }
}
#-----


Report •

Related Solutions

#4
February 19, 2012 at 23:48:10
Dear Friend,
Actually, I wanted to remove unwanted space in every last element of each line,
what we get when replace the line "if (wt == 7 && k == cnt)" with "if (wt == 7)."
Now, although it goes a little slower, but that's it.
I would not want to bother you more.
What was essentially you solved, and rest I'll try alone.
Once again, thanks a lot for your help.
Regards,
imrsi25

Report •

Ask Question