Maximum Length Difference

You are given two arrays a1 and a2 of strings. Each string is composed with letters from a to z. Let x be any string in the first array and y be any string in the second array.

Find max(abs(length(x) − length(y)))

If a1 and/or a2 are empty return -1 in each language except in Haskell (F#) where you will return Nothing (None).

Example:

a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]
a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
mxdiflg(a1, a2) --> 13

Bash note:

  • input : 2 strings with substrings separated by ,
  • output: number as a string
#!/bin/bash
# input : 2 strings with substrings separated by `,`
# output: number as a string
accum () {
    a1=$1
    a2=$2
    my_count(){
      let count=`echo $1 | awk -F',' '{print NF}'`-1
      printf  "%d"  $count
    }
    
    str_len(){
      str_len=${#1}
      printf "%d" $str_len
    }
    
    my_mm(){
      count=`my_count $1`
      a_list=($(echo $1 | tr ',' ' '))
 
      for i in `seq 0 $count`
      do
        len[$i]=`str_len ${a_list[$i]}`
      done

      new_len=($(echo ${len[@]} | tr ' ' '\n' | sort -n))
      printf "%d\n%d" ${new_len[0]} ${new_len[-1]}
    }

    my_accum(){
    a1_list=($(my_mm $1))
    a2_list=($(my_mm $2))
    let accum1=a2_list[-1]-a1_list[0]
    let accum2=a1_list[-1]-a2_list[0]
    [ "$accum1" -ge "$accum2" ] && echo "$accum1" || echo "$accum2" 
    }
    
    if [ -n "$1" ] && [ -n "$2" ];then
      echo `my_accum $1 $2`
    else
      echo "-1"
    fi
}
accum "$1" "$2"

 

posted @ 2022-06-19 14:58  zk01  阅读(23)  评论(0编辑  收藏  举报