TransWikia.com

replace every second value in a sequence with special character '*'

Unix & Linux Asked by codeholic24 on January 24, 2021

Let’s take Input from user as 9. So the Fibonacci series upto 9 is as follow’s 0,1,1,2,3,5,8,13,21

Expected Output : 0,*,1,*,3,*,8,*,21

Below is the following code which i work around to implement logic

UserInput=9 
a=0 
b=1 

echo "The Fibonacci series is  : "

for (( i=0; i<UserInput; i++ )) 
do
    if [ $i -eq 2 ]
    then 
        echo -n "$a "
        sn=$((a + b)) 
        a=$b 
        b=$sn 
    fi 
done

2 Answers

Mandatory awk-based solution (where for simplicity I will assume n>2):

awk -v n=9 'BEGIN{q=1; printf "0,*,"; for (i=2;i<n;i++) {s=q+r;r=q;q=s; printf "%s%s",i%2?"*":s,i==n-1?"n":","}}'

The user input is stored in the variable n and passed to awk via the command-line argument -v n=number.

In order to exit immediately if n<3:

awk -v n=9 'BEGIN{if (n<3) exit; q=1; printf "0,*,"; for (i=2;i<n;i++) {s=q+r;r=q;q=s; printf "%s%s",i%2?"*":s,i==n-1?"n":","}}'

Explanation

awk is a text-processing tool, we are "creatively misusing" it. Therefore, everything happens inside the BEGIN block which usually contains code executed before the first input file is processed.

The syntax itself is very C-like, so we

  • print the first two terms of the series (which are fixed since we assume n>2): printf "0,*,"
  • loop from 2 to n-1 and calculate the Fibonaccy number s as sum of the two previous ones q and r, and update q and r
  • print either * if i is even, or the current Fibonacci number s if it is not (i%2?"*":s)
  • and print either a , or a newline after that, depending on whether we have reached the end of the loop (i==n-1) or not.

Correct answer by AdminBee on January 24, 2021

The closest to your code, using Bash and arithmetic operators is this:

#!/bin/bash
let UserInput=9 
let a=0 
let b=1
echo -n "The Fibonacci series is: 0"
for (( i=1; i<UserInput; i++ )) ; do
  let sn=a+b
  let a=b
  let b=sn
  if (( i % 2 == 0 )) ; then 
    echo -n ",$a"
  else
    echo -n ",*"
  fi 
done
echo

In the if statement you have to use the % modulo (remainder) operator. Using it you can test whether i is divisible to two (i.e. an even number) and print the value of $a or print a * accordingly.

The output will be:

The Fibonacci series is: 0,*,1,*,3,*,8,*,21

To change the script, so that it gets the number of steps from its argument, please modify the first line of the script like this:

let UserInput="$1"

Answered by FedonKadifeli on January 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP