Sort by

recency

|

195 Discussions

|

  • + 0 comments

    tr " " "\n" | tail +2 | sort | uniq -u tr is used so each array element in new line for further processing tail is used to skip 1st line which contain total no. of array elements sort for uniq cmd to work as desired uniq -u print only the uniq element

  • + 0 comments
    read N
    readarray numbers
    printf "%s\n" ${numbers[@]} | sort -rn | uniq -u
    
  • + 0 comments
    read N
    read -a arr
    
    # We create the variable found to help us iterate
    found=0
    while [[ ${#arr[@]} -gt 1 ]]; do
        # We create an array with the existent indexes
        idx=()
        for i in ${!arr[@]}; do
            idx+=("$i")
        done
        
        # We pick the first value
        check=${arr[${idx[$found]}]}
        
        # We start the counter of matches
        count=0
        
        # We check the array counting matches
        for i in ${!arr[@]}; do
            if [[ "${arr[$i]}" -eq "$check" ]]; then
                ((count++))
            fi
        done
        
        # We check how many matches we have
        if [[ $count -eq 2 ]]; then
            # If we have 2 matcher, we delete ALL matches
            for i in ${!arr[@]}; do
                if [[ "${arr[$i]}" -eq "$check" ]]; then
                    unset arr[$i]
                fi
            done
        else
            # Else, we have 1 match, aka the lonely integer
            # We increase the found, so the check value skips the one
            ((found++))
        fi
    done
    echo "${arr[@]}"
    
  • + 0 comments

    in case if you don't want to use sort | uniq etc. for some reason:

    #!/bin/sh
    
    read dummy
    read -a ARRAY
    FILTER=()
    
    # X (listof X) -> Boolean
    member () {
      for i in ${@:2}; do
        if [[ $1 -eq $i ]]; then
            return 0
        fi
      done
      return 1
    }
    
    # X (listof X) -> (listof X)
    filter () {
      new=()
      for i in ${@:2}; do
        if ! [[ $i -eq $1 ]]; then
            new+=($i)
        fi
      done
      # bash functions don't return values, so we use global vars instead
      FILTER=${new[@]}
    }
    
    # (listof X) -> X
    lonelyint () {
      # () to properly create an array from element
      array=("$@")
      count=0
    
      for current in ${array[@]}; do
        let 'count++'
        rest=${array[@]:$count}
        if member $current $rest; then
            # this filter doesn't really work
            # array=(2 32 2) current=2 => array=(3)
            #new=${array[@]/$current/}
            filter $current ${array[@]}
            lonelyint ${FILTER[@]}
        else
            echo "$current"
            exit 0
        fi
      done
    }
    
    lonelyint ${ARRAY[@]}
    
  • + 0 comments

    read n

    mapfile -t arr

    arr=({arr[@]}" | tr ' ' '\n' | sort -n | uniq -u))

    echo "${arr[@]}"