posted by 귀염둥이채원 2021. 9. 15. 11:02

Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[]. The array might also contain duplicates. You may assume that both x and y are different and present in arr[].

 

Example

Input: arr[] = {1, 2}, x = 1, y = 2
Output: Minimum distance between 1 
and 2 is 1.
Explanation: 1 is at index 0 and 2 is at 
index 1, so the distance is 1

Input: arr[] = {3, 4, 5}, x = 3, y = 5
Output: Minimum distance between 3 
and 5 is 2.
Explanation:3 is at index 0 and 5 is at 
index 2, so the distance is 2

Input: 
arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3},  
x = 3, y = 6
Output: Minimum distance between 3 
and 6 is 4.
Explanation:3 is at index 0 and 6 is at 
index 5, so the distance is 4

Input: arr[] = {2, 5, 3, 5, 4, 4, 2, 3}, 
x = 3, y = 2
Output: Minimum distance between 3 
and 2 is 1.
Explanation:3 is at index 7 and 2 is at 
index 6, so the distance is 1
# Python3 code to Find the minimum
# distance between two numbers
 
 
def minDist(arr, n, x, y):
    min_dist = 99999999
    for i in range(n):
        for j in range(i + 1, n):
            if (x == arr[i] and y == arr[j] or
                    y == arr[i] and x == arr[j]) and min_dist > abs(i-j):
                min_dist = abs(i-j)
        return min_dist
 
 
# Driver code
arr = [3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3]
n = len(arr)
x = 3
y = 6
print("Minimum distance between ", x, " and ",
      y, "is", minDist(arr, n, x, y))
import sys
 
def minDist(arr, n, x, y):
     
    #previous index and min distance
    i=0
    p=-1
    min_dist = sys.maxsize;
     
    for i in range(n):
     
        if(arr[i] ==x or arr[i] == y):
         
            #we will check if p is not equal to -1 and
            #If the element at current index matches with
            #the element at index p , If yes then update
            #the minimum distance if needed
            if(p != -1 and arr[i] != arr[p]):
                min_dist = min(min_dist,i-p)
              
            #update the previous index
            p=i
         
     
    #If distance is equal to int max
    if(min_dist == sys.maxsize):
       return -1
    return min_dist
 
  
# Driver program to test above function */
arr = [3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3]
n = len(arr)
x = 3
y = 6
print ("Minimum distance between %d and %d is %d\n"%( x, y,minDist(arr, n, x, y)));

 

 

posted by 귀염둥이채원 2021. 9. 15. 10:55

Given two sorted arrays, find their union and intersection.

Input : arr1[] = {1, 3, 4, 5, 7}
        arr2[] = {2, 3, 5, 6} 
Output : Union : {1, 2, 3, 4, 5, 6, 7} 
         Intersection : {3, 5}

Input : arr1[] = {2, 5, 6}
        arr2[] = {4, 6, 8, 10} 
Output : Union : {2, 4, 5, 6, 8, 10} 
         Intersection : {6}
# Python program to find union of
# two sorted arrays
# Function prints union of arr1[] and arr2[]
# m is the number of elements in arr1[]
# n is the number of elements in arr2[]
def printUnion(arr1, arr2, m, n):
    i, j = 0, 0
    while i < m and j < n:
        if arr1[i] < arr2[j]:
            print(arr1[i])
            i += 1
        elif arr2[j] < arr1[i]:
            print(arr2[j])
            j+= 1
        else:
            print(arr2[j])
            j += 1
            i += 1
 
    # Print remaining elements of the larger array
    while i < m:
        print(arr1[i])
        i += 1
 
    while j < n:
        print(arr2[j])
        j += 1
 
# Driver program to test above function
arr1 = [1, 2, 4, 5, 6]
arr2 = [2, 3, 5, 7]
m = len(arr1)
n = len(arr2)
printUnion(arr1, arr2, m, n)
# Python3 program to find union of two
# sorted arrays (Handling Duplicates)
def UnionArray(arr1, arr2):
     
    # Taking max element present in either array
    m = arr1[-1]
    n = arr2[-1]
    ans = 0
         
    if m > n:
        ans = m
    else:
        ans = n
         
    # Finding elements from 1st array
    # (non duplicates only). Using
    # another array for storing union
    # elements of both arrays
    # Assuming max element present
    # in array is not more than 10 ^ 7
    newtable = [0] * (ans + 1)
         
    # First element is always
    # present in final answer
    print(arr1[0], end = " ")
         
    # Incrementing the First element's count
    # in it's corresponding index in newtable
    newtable[arr1[0]] += 1
         
    # Starting traversing the first
    # array from 1st index till last
    for i in range(1, len(arr1)):
         
        # Checking whether current element
        # is not equal to it's previous element
        if arr1[i] != arr1[i - 1]:
             
            print(arr1[i], end = " ")
            newtable[arr1[i]] += 1
             
    # Finding only non common
    # elements from 2nd array        
    for j in range(0, len(arr2)):
         
        # By checking whether it's already
        # present in newtable or not
        if newtable[arr2[j]] == 0:
             
            print(arr2[j], end = " ")
            newtable[arr2[j]] += 1
     
# Driver Code
if __name__ == "__main__":
     
    arr1 = [1, 2, 2, 2, 3]
    arr2 = [2, 3, 4, 5]
         
    UnionArray(arr1, arr2)
# Python3 program to find Intersection of two
# Sorted Arrays (Handling Duplicates)
def IntersectionArray(a, b, n, m):
    '''
    :param a: given sorted array a
    :param n: size of sorted array a
    :param b: given sorted array b
    :param m: size of sorted array b
    :return: array of intersection of two array or -1
    '''
 
    Intersection = []
    i = j = 0
     
    while i < n and j < m:
        if a[i] == b[j]:
 
            # If duplicate already present in Intersection list
            if len(Intersection) > 0 and Intersection[-1] == a[i]:
                i+= 1
                j+= 1
 
            # If no duplicate is present in Intersection list
            else:
                Intersection.append(a[i])
                i+= 1
                j+= 1
        elif a[i] < b[j]:
            i+= 1
        else:
            j+= 1
             
    if not len(Intersection):
        return [-1]
    return Intersection
 
# Driver Code
if __name__ == "__main__":
 
    arr1 = [1, 2, 2, 3, 4]
    arr2 = [2, 2, 4, 6, 7, 8]
     
    l = IntersectionArray(arr1, arr2, len(arr1), len(arr2))
    print(*l)

 

 

posted by 귀염둥이채원 2021. 9. 15. 10:46

Given two binary arrays, arr1[] and arr2[] of the same size n. Find the length of the longest common span (i, j) where j >= i such that arr1[i] + arr1[i+1] + …. + arr1[j] = arr2[i] + arr2[i+1] + …. + arr2[j].
The expected time complexity is Θ(n).

Examples:

Input: arr1[] = {0, 1, 0, 0, 0, 0};
arr2[] = {1, 0, 1, 0, 0, 1};
Output: 4
The longest span with same sum is from index 1 to 4.

Input: arr1[] = {0, 1, 0, 1, 1, 1, 1};
arr2[] = {1, 1, 1, 1, 1, 0, 1};
Output: 6
The longest span with same sum is from index 1 to 6.

Input: arr1[] = {0, 0, 0};
arr2[] = {1, 1, 1};
Output: 0

Input: arr1[] = {0, 0, 1, 0};
arr2[] = {1, 1, 1, 1};
Output: 1
We strongly recommend that you click here and practice it, before moving on to the solution.
Method 1 (Simple Solution)
One by one by consider same subarrays of both arrays. For all subarrays, compute sums and if sums are same and current length is more than max length, then update max length. Below is C++ implementation of the simple approach.


Method 1 (Simple Solution)

# A Simple python program to find longest common
# subarray of two binary arrays with same sum

# Returns length of the longest common subarray
# with same sum
def longestCommonSum(arr1, arr2, n):

	# Initialize result
	maxLen = 0

	# One by one pick all possible starting points
	# of subarrays
	for i in range(0,n):

		# Initialize sums of current subarrays
		sum1 = 0
		sum2 = 0

		# Consider all points for starting with arr[i]
		for j in range(i,n):
	
			# Update sums
			sum1 += arr1[j]
			sum2 += arr2[j]

			# If sums are same and current length is
			# more than maxLen, update maxLen
			if (sum1 == sum2):
				len = j-i+1
				if (len > maxLen):
					maxLen = len
	
	return maxLen


# Driver program to test above function
arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
n = len(arr1)
print("Length of the longest common span with same "
			"sum is",longestCommonSum(arr1, arr2, n))


Method 2 (Using Auxiliary Array)

# Python program to find longest common
# subarray of two binary arrays with
# same sum

def longestCommonSum(arr1, arr2, n):

	# Initialize result
	maxLen = 0
	
	# Initialize prefix sums of two arrays
	presum1 = presum2 = 0
	
	# Create a dictionary to store indices
	# of all possible sums
	diff = {}
	
	# Traverse both arrays
	for i in range(n):
	
		# Update prefix sums
		presum1 += arr1[i]
		presum2 += arr2[i]
		
		# Compute current diff which will be
		# used as index in diff dictionary
		curr_diff = presum1 - presum2
		
		# If current diff is 0, then there
		# are same number of 1's so far in
		# both arrays, i.e., (i+1) is
		# maximum length.
		if curr_diff == 0:
			maxLen = i+1
		elif curr_diff not in diff:
			# save the index for this diff
			diff[curr_diff] = i
		else:				
			# calculate the span length
			length = i - diff[curr_diff]
			maxLen = max(maxLen, length)
		
	return maxLen

# Driver program
arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
print("Length of the longest common",
	" span with same", end = " ")
print("sum is",longestCommonSum(arr1,
				arr2, len(arr1)))



Method 3 (Using Hashing)

# Python program to find largest subarray
# with equal number of 0's and 1's.

# Returns largest common subarray with equal
# number of 0s and 1s
def longestCommonSum(arr1, arr2, n):
	
	# Find difference between the two
	arr = [0 for i in range(n)]
	
	for i in range(n):
		arr[i] = arr1[i] - arr2[i];
	
	# Creates an empty hashMap hM
	hm = {}
	sum = 0	 # Initialize sum of elements
	max_len = 0	 #Initialize result
	
	# Traverse through the given array
	for i in range(n):
		
		# Add current element to sum
		sum += arr[i]
		
		# To handle sum=0 at last index
		if (sum == 0):
			max_len = i + 1
		
		# If this sum is seen before,
		# then update max_len if required
		if sum in hm:
			max_len = max(max_len, i - hm[sum])
		else: # Else put this sum in hash table
			hm[sum] = i
	return max_len

# Driver code
arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
n = len(arr1)
print(longestCommonSum(arr1, arr2, n))

 

 

posted by 귀염둥이채원 2021. 4. 23. 01:15

expect는 다른 응용 어플리케이션과 상호대화(interactive)하는 프로그램을 만들기 위해 만들어진 프로그램이다.
expect를 이용하면 다른 어플리케이션과 상호대화를 할수 있게 됨으로 자동화된 프로그램을 만들수가 있다.

ssh 접속

#!/bin/sh
USER=testuser
IP=192.168.10.2
PW=testpw
expect <<EOF
set timeout 3
spawn ssh -o StrictHostKeyChecking=no $USER@$IP "hostname"
expect "password:"
    send "$PW\r"
expect eof
EOF

hue 신규 계정 생성

#!/bin/bash

sudo yum install -y expect

expect <<EOF
spawn /usr/lib/hue/build/env/bin/hue createsuperuser
expect "Username (leave blank to use 'hadoop'):" {send "hue\r"}
expect "Email address:" {send "hue@email.com\r"}
expect "Password" {send "Huereco1!\r"}
expect "Password (again)" {send "Huereco1!\r"}
expect eof
EOF

참고사이트

https://zetawiki.com/wiki/Bash_%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%EC%97%90_expect_%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8_%EB%84%A3%EA%B8%B0
https://must-thanks.tistory.com/156
https://zetawiki.com/wiki/%EB%A6%AC%EB%88%85%EC%8A%A4_expect
posted by 귀염둥이채원 2021. 4. 23. 00:51

IFS는 Internal Field Separator의 약자로 외부프로그램을 실행할 때 입력되는 문자열을 나눌 때 기준이 되는 문자를 정의하는 변수이다.
bash의 내부 필드 구분자(internal field separator)가 공백/탭/줄바꿈이다.
구분자는 IFS 변수에 설정되어 있다.

PROGRAMMING="
java programming
python programming
c programming
"

echo "-------------------------"
for p in $PROGRAMMING; do
echo $p
done

# IFS를 줄바꿈(newline)로 변경
echo "-------------------------"
OLD_IFS="$IFS"
IFS=$'\n'
for p in $PROGRAMMING; do
echo $p
done

IFS="$OLD_IFS"
$ bash test.sh
-------------------------
java
programming
python
programming
c
programming
-------------------------
java programming
python programming
c programming

# 참고사이트
https://m31phy.tistory.com/11
https://webterror.net/?p=1716
https://wooono.tistory.com/186

posted by 귀염둥이채원 2021. 4. 22. 19:44

시작날짜, 종료날짜를 입력해서 매주 일요일, 화요일만 수행하는 스크립트 샘플입니다.

 

CLUSTER_ID="5FFZMTA6C"
BATCH_START_DATE="20210228"
BATCH_END_DATE="20210420"

while true; do
  if [ $BATCH_START_DATE -gt $BATCH_END_DATE ]; then
      exit 0
  fi

  day_of_week=$(date -d "${BATCH_START_DATE}" "+%A")
  if [ $day_of_week == "Sunday" ] || [ $day_of_week == "Tuesday" ]; then
    DISP_START_DATE=$(date -d "${BATCH_START_DATE} +1days" "+%Y%m%d")
    DISP_END_DATE=$(date -d "${BATCH_START_DATE} +7days" "+%Y%m%d")
    echo "BATCH: $BATCH_START_DATE"
    echo "./backfill.sh $_CLUSTER_ID stat $DISP_START_DATE $DISP_END_DATE;"
  fi

  sleep 0.1
  BATCH_START_DATE=$(date -d "${BATCH_START_DATE} +1days" "+%Y%m%d")
done

 

$ bash test7.sh | grep backfill
./backfill.sh  stat 20210301 20210307;
./backfill.sh  stat 20210303 20210309;
./backfill.sh  stat 20210308 20210314;
./backfill.sh  stat 20210310 20210316;
./backfill.sh  stat 20210315 20210321;
./backfill.sh  stat 20210317 20210323;
./backfill.sh  stat 20210322 20210328;
./backfill.sh  stat 20210324 20210330;
./backfill.sh  stat 20210329 20210404;
./backfill.sh  stat 20210331 20210406;
./backfill.sh  stat 20210405 20210411;
./backfill.sh  stat 20210407 20210413;
./backfill.sh  stat 20210412 20210418;
./backfill.sh  stat 20210414 20210420;
./backfill.sh  stat 20210419 20210425;
./backfill.sh  stat 20210421 20210427;​
posted by 귀염둥이채원 2021. 4. 15. 18:51

---------------------------------------------------------

# 디버깅 - set 옵션들 (-e, -u, -x)

---------------------------------------------------------

set은 쉘의 옵션을 설정하는 명령어이다.

-e, -u 옵션을 설정하면 스크립트에서 문제가 발생한것을 찾을수 있다.

* -e: 쉘 스크립트 실행 중에 0이 아닌 값으로 exit을 한 명령이 있으면 나머지 스크립트를 실행하지 않은 채 exit한다.

* -u: 정의되지 않은 변수(undefined)를 참조하면 에러를 출력하며 바로 exit한다.

* -x: 쉘 스크립트가 실행하는 모든 명령을 화면에 출력한다. 디버깅에 유용하다.

 

# 쉘스크립트의 도입부에 다음과 같이 적으면 된다.

set -e -u -x

 

# bash xxx.sh 실행시 옵션 적용

bash -x xxx.sh

bash -eux xxx.sh

 

---------------------------------------------------------

# example1: 스크립트내에서 -e, -u, -x 설정

---------------------------------------------------------

#!/bin/bash

set -e -u -x



NUM=100

echo $NUM



TIME=`date`

echo $TIME



echo $UNDIFIED
# output

$ bash test.sh

+ NUM=100

+ echo 100

100

++ date

+ TIME='2021년 4월 10일 토요일 03시 19분 28초 KST'

2021년 4월 10일 토요일 03시 19분 28초 KST

test.sh: line 9: UNDIFIED: unbound variable

 

---------------------------------------------------------

# example2: 스크립트 실행시 -e 옵션 설정

---------------------------------------------------------

#!/bin/bash

echo $UNDIFIED



NUM=100

echo $NUM



TIME=`date`

echo $TIME
# output

$ bash -e test.sh



100

2021년 4월 10일 토요일 03시 21분 42초 KST

 

---------------------------------------------------------

# 참고사이트

---------------------------------------------------------

https://blog.kkeun.net/computer/2016-08-24-bash-good

https://118k.tistory.com/201

https://frankler.tistory.com/59

 

posted by 귀염둥이채원 2021. 4. 15. 17:22

#!/bin/bash
# -- ABOUT THIS PROGRAM: ------------------------------------------------------
#
# Author:       fang
# Version:      1.0.0
# Description:  description goes here
#
# ------------------------------------------------------------------------------
# | VARIABLES                                                                  |
# ------------------------------------------------------------------------------
VERSION="1.0.0"

# ------------------------------------------------------------------------------
# | UTILS                                                                      |
# ------------------------------------------------------------------------------
log_dbg() {
    printf "$(tput setaf 3)→ %s$(tput sgr0)\n" "$@"
}

log_svc() {
    printf "$(tput setaf 76)✔ %s$(tput sgr0)\n" "$@"
}

log_err() {
    printf "$(tput setaf 1)✖ %s$(tput sgr0)\n" "$@"
}

# ------------------------------------------------------------------------------
# | MAIN FUNCTIONS                                                             |
# ------------------------------------------------------------------------------
usage() {
    cat <<EOF
------------------------------------------------------------------------------
| DESCRIPTION
------------------------------------------------------------------------------
Usage: $0 [options]
Example: $0

Options:
    -h, --help      output program instructions
    -v, --version   output program version

EOF
}

version() {
    echo "$0: v$VERSION"
}

run() {
    # your code goes here
    log_dbg "log_dbg"
    log_svc "log_svc"
    log_err "log_err"
}

# ------------------------------------------------------------------------------
# | INITIALIZE PROGRAM                                                         |
# ------------------------------------------------------------------------------
main() {
    if [[ "${1}" == "-h" || "${1}" == "--help" ]]; then
        usage ${1}
        exit 1
    elif [[ "${1}" == "-v" || "${1}" == "--version" ]]; then
        version ${1}
        exit 1
    else
        run
    fi
}

# Initialize
main $*

posted by 귀염둥이채원 2021. 4. 15. 13:35

---------------------------------------------------------

# trap example

---------------------------------------------------------

#!/bin/bash

# bash trap command

trap bashtrap INT

 

# bash clear screen command

clear

 

# bash trap function is executed when CTRL-C is pressed:

# bash prints message => Executing bash trap subrutine !

bashtrap() {

echo "CTRL+C Detected !...executing bash trap !"

}

 

# for loop from 1/10 to 10/10

for a in $(seq 1 10); do

echo "$a/10 to Exit."

sleep 1

done

echo "Exit Bash Trap Example!!!"

 

# output1

$ bash test.sh

1/10 to Exit.

2/10 to Exit.

3/10 to Exit.

4/10 to Exit.

5/10 to Exit.

6/10 to Exit.

7/10 to Exit.

8/10 to Exit.

9/10 to Exit.

10/10 to Exit.

Exit Bash Trap Example!!!

 

# output2

$ bash test.sh

1/10 to Exit.

2/10 to Exit.

^CCTRL+C Detected !...executing bash trap !

3/10 to Exit.

^CCTRL+C Detected !...executing bash trap !

4/10 to Exit.

^CCTRL+C Detected !...executing bash trap !

5/10 to Exit.

^CCTRL+C Detected !...executing bash trap !

6/10 to Exit.

7/10 to Exit.

8/10 to Exit.

9/10 to Exit.

^CCTRL+C Detected !...executing bash trap !

10/10 to Exit.

Exit Bash Trap Example!!!

 

'쉘스크립트' 카테고리의 다른 글

[Shell Script] 디버깅  (0) 2021.04.15
[Shell Script] template source code  (0) 2021.04.15
[Shell Script] 함수(function)  (0) 2021.04.15
[Shell Script] 반복문(while)  (0) 2021.04.15
[Shell Script] 반복문(for)  (0) 2021.04.15
posted by 귀염둥이채원 2021. 4. 15. 12:38

 

---------------------------------------------------------

# 함수(Function)

---------------------------------------------------------

* function는 생략해도 된다.

* 함수명을 쓰면 함수가 호출이 된다.

* 호출 코드가 함수 코드보다 반드시 뒤에 있어야 된다.

- 함수 코드 보다 앞에서 호출 오류가 발생한다.

 

---------------------------------------------------------

# 함수 예시

---------------------------------------------------------

#!/bin/bash

string_test1() {

echo "string test1"

}

 

function string_test2() {

echo "string test2"

echo -n "인자값: ${@}"

}

 

string_test1

string_test2

 

# 함수에 인자값 전달하기(공백으로 띄워서 2개의 인자값을 넘김)

string_test2 "hello" "world"

 

# output

$ bash test.sh

string test1

string test2

인자값: string test2

인자값: hello world

 

---------------------------------------------------------

# example

---------------------------------------------------------

#!/bin/bash

# BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER

function function_B {

echo Function B.

}

function function_A {

echo $1

}

function function_D {

echo Function D.

}

function function_C {

echo $1

}

# FUNCTION CALLS

# Pass parameter to function A

function_A "Function A."

function_B

# Pass parameter to function C

function_C "Function C."

function_D

 

# output

$ bash test.sh

Function A.

Function B.

Function C.

Function D.

 

---------------------------------------------------------

# 문자열을 반환하는 방법 - 전역변수 사용

---------------------------------------------------------

* 전역 변수를 사용하여 문자열 값을 반환

* 함수를 호출 한 후 전역 변수의 값이 변경



#!/bin/bash

function F1() {

retval='I like programming'

}

 

retval='I hate programming'

echo $retval

F1

echo $retval

 

# output

$ bash test.sh

I hate programming

I like programming

 

---------------------------------------------------------

# 문자열을 반환하는 방법 - 함수 명령 사용

---------------------------------------------------------

#!/bin/bash

function F2() {

local retval='Using BASH Function'

echo "$retval"

}

 

getval=$(F2)

echo $getval

 

# output

$ bash test.sh

Using BASH Function

 

---------------------------------------------------------

# 문자열을 반환하는 방법 - 변수 사용

---------------------------------------------------------

#!/bin/bash

function F3() {

local arg1=$1

 

if [[ $arg1 != "" ]]; then

retval="BASH function with variable"

else

echo "No Argument"

fi

}

 

getval1="Bash Function"

F3 $getval1

echo $retval

 

getval2=$(F3)

echo $getval2

 

# output

$ bash test.sh hello

BASH function with variable

No Argument

 

---------------------------------------------------------

# 문자열을 반환하는 방법 - Return 문 사용

---------------------------------------------------------

#!/bin/bash

function F4() {

echo 'Bash Return Statement'

return 35

}

 

F4

echo "Return value of the function is $?"

 

# output

$ bash test.sh hello

Bash Return Statement

Return value of the function is 35

 

---------------------------------------------------------

# 참고사이트

---------------------------------------------------------

https://devhints.io/bash

https://blog.gaerae.com/2015/01/bash-hello-world.html