Home > Enterprise >  Regularly spaced numbers between bounds without jot
Regularly spaced numbers between bounds without jot

Time:09-20

I want to generate a sequence of integer numbers between 2 included bounds. I tried with seq, but I could only get the following:

$ low=10
$ high=100
$ n=8
$ seq $low $(( (high-low) / (n-1) )) $high
10
22
34
46
58
70
82
94

As you can see, the 100 is not included in the sequence.

I know that I can get something like that using jot:

$ jot 8 10 100
10
23
36
49
61
74
87
100

But the server I use does not have jot installed, and I do not have permission to install it.

Is there a simple method that I could use to reproduce this behaviour without jot?

CodePudding user response:

If you don't mind launching an extra process (bc) and if it's available on that machine, you could also do it like this:

$ seq -f'%.f' 10 $(bc <<<'scale=2; (100 - 10) / 7') 100
10
23
36
49
61
74
87
100

Or, building on oguz ismail's idea (but using a precision of 4 decimal places):

$ declare -i low=10
$ declare -i high=100
$ declare -i n=8
$ declare incr=$(( (${high}0000 - ${low}0000) / (n - 1) ))
$ 
$ incr=${incr::-4}.${incr: -4}
$ 
$ seq -f'%.f' "$low" "$incr" "$high"
10
23
36
49
61
74
87
100

CodePudding user response:

You can try this naive implementation of jot:

jot_naive() {
  local -i reps=$1 begin=${2}00 ender=${3}00
  local -i x step='(ender - begin) / (reps - 1)'
  for ((x = begin; x <= ender; x  = step)); do
    printf '%.f\n' ${x::-2}.${x: -2}
  done
}

CodePudding user response:

You could use awk for that:

awk -v reps=8 -v begin=10 -v end=100 '
    BEGIN{
        step = (end - begin) / (reps-1);
        for ( f = i = begin; i <= end; i = int(f  = step) )
            print i
    }
'
10
22
35
48
61
74
87
100
  • Related