물음표 살인마의 개발블로그

알고리즘 문제/CodeWar

Split and then add both sides of an array together.

BEstyle 2022. 11. 23. 13:15

DESCRIPTION:

Inspired by the Fold an Array kata. This one is sort of similar but a little different.


Task

You will receive an array as parameter that contains 1 or more integers and a number n.

Here is a little visualization of the process:

  • Step 1: Split the array in two:
  • [1, 2, 5, 7, 2, 3, 5, 7, 8] / \ [1, 2, 5, 7] [2, 3, 5, 7, 8]
  • Step 2: Put the arrays on top of each other:
  • [1, 2, 5, 7] [2, 3, 5, 7, 8]
  • Step 3: Add them together:
  • [2, 4, 7, 12, 15]

Repeat the above steps n times or until there is only one number left, and then return the array.

Example

Input: arr=[4, 2, 5, 3, 2, 5, 7], n=2


Round 1
-------
step 1: [4, 2, 5]  [3, 2, 5, 7]

step 2:    [4, 2, 5]
        [3, 2, 5, 7]

step 3: [3, 6, 7, 12]


Round 2
-------
step 1: [3, 6]  [7, 12]

step 2:  [3,  6]
         [7, 12]

step 3: [10, 18]


Result: [10, 18]

def split_and_add(numbers, n):
    count=0
    while len(numbers)!=1 and count!=n:
        count+=1
        numbers=adda(splita(numbers)[0],splita(numbers)[1])
    return numbers

def splita(array):
    ans=[]
    if len(array)%2==0:
        ans.append(array[:int(len(array)/2)])
        ans.append(array[int(len(array)/2):])
    else:
        ans.append( array[: int(len(array)/2-0.5)])
        ans.append( array[int(len(array)/2-0.5):])
    return ans
    
def adda(array1,array2):
    ans=[]
    if len(array1)==len(array2):
        for i in range(len(array1)):
            ans.append(array1[i]+array2[i])
    else:
        ans.append(array2[0])
        for i in range(len(array1)):
            ans.append(array1[i]+array2[i+1])
    return ans

'알고리즘 문제 > CodeWar' 카테고리의 다른 글

Clocky Mc Clock-Face  (0) 2022.11.24
The Office V - Find a Chair  (0) 2022.11.24
Who has the most money?  (0) 2022.11.23
Sorting on planet Twisted-3-7  (0) 2022.11.22
Financing Plan on Planet XY140Z-n  (0) 2022.11.22