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

알고리즘 문제/CodeWar

Fold an array

BEstyle 2022. 10. 17. 13:10

DESCRIPTION:

In this kata you have to write a method that folds a given array of integers by the middle x-times.

An example says more than thousand words:

Fold 1-times:
[1,2,3,4,5] -> [6,6,3]

A little visualization (NOT for the algorithm but for the idea of folding):

 Step 1         Step 2        Step 3       Step 4       Step5
                     5/           5|         5\          
                    4/            4|          4\      
1 2 3 4 5      1 2 3/         1 2 3|       1 2 3\       6 6 3
----*----      ----*          ----*        ----*        ----*


Fold 2-times:
[1,2,3,4,5] -> [9,6]

def ips_between(start, end):
    fnlist=start.split(".")
    snlist=end.split(".")
    fn=0
    sn=0
    for i in range(len(fnlist)):
        fn+=int(fnlist[3-i])*(256**i)
        sn+=int(snlist[3-i])*(256**i)
    return sn-fn

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

Valid Phone Number  (0) 2022.10.18
Count IP Addresses  (0) 2022.10.18
Triple trouble  (0) 2022.10.17
Count the Digit  (0) 2022.10.16
Breaking Chocolate Problem  (0) 2022.10.16