Generating Random Strings and Save them Sorted

I gave a challenge to myself, which is to generate random strings and insert them sorted, using binary search, into a JSON file. Sounds easy right? No really, I wanted to do it without a real common programming language, but only Bash, JQ and OpenSSL. JQ is arguably a programmable itself.

JQ has a nice function called bsearch that implements binary search. That gave me a motivation for the challenge as well.

You can think of the problem yourself, and try it on your own, before you read the solution that I came up with.

Here is the code. I will keep improving it, in case I come up with more interesting ideas or challenges.

echo '[]' > data.json

for run in {1..100}; do
  jq --arg value "$(openssl rand -hex 6)" '{value: $value} as $item | bsearch($item) as $ix | if $ix < 0 then . = .[0:-(1 + $ix)] + [$item] + .[-(1 + $ix):] else . = .[0:$ix] + [$item] + .[$ix:] end' data.json | sponge data.json

jq '.|length as $length| "The length of the array inside data.json is \($length)"' data.json

If you can think of a better way to write this code, please write me @OmarQunsul

About Me

My name is Omar Qunsul. I write these articles mainly as a future reference for me. So I dedicate some time to make them look shiny, and share them with the public.

You can find me on twitter @OmarQunsul, and on Linkedin.