태그 보관물: code-golf

code-golf

호박 여행 문제 호박마다 호박

배경:

잭은 모든 호박마다 호박 밭 근처에있는 마을 사람들을 놀라게하는 호박입니다. 그러나 매년 누군가가 촛불을 켜면 촛불이 타기 전에 모든 사람을 놀라게 할 시간이 제한되어 있으므로 아무도 그를 볼 수 없기 때문에 더 이상 마을 사람들을 놀라게 할 수 없습니다. 지난 몇 년 동안, 그는 의사 결정이 어려워서 소량의 마을 만 sp을 수 있었지만 이제는 당신을 도와야하므로 최대한 많은 마을을 sp을 수있을 것입니다!

태스크:

마을 위치 목록과 양초 수명이 주어지면 Jack이 방문 할 수있는 최대 마을 수를 출력합니다. 경로 자체를 인쇄 할 필요는 없습니다.

입력:

촛불의 수명과 직교 좌표계의 마을 위치 목록. 호박 패치 잭의 기원은 항상 0,0입니다. 원하는대로 입력을 포맷 할 수 있습니다. Jack의 움직임을 단순화하기 위해 수평, 수직 또는 대각선으로 만 움직일 수 있습니다. 즉, 촛불이 움직일 때마다 1 또는 1.5 (대각선이 약간 길어집니다)의 생명력이 손실됩니다. 수명이 0보다 작거나 같으면 양초가 타 버립니다.

산출:

양초가 타기 전에 Jack이 방문 할 수있는 최대 마을 수와 동일한 정수입니다.

규칙 :

이것은 이므로 바이트 단위의 가장 짧은 코드가 이깁니다. 표준 허점은 허용되지 않습니다.

테스트 사례 :

// Format [lifespan] [list of village coordinates] -> [maximum visit-able villages]

4 -1,0 1,0 2,0 3,0 4,0 5,0 -> 3
4 1,1 2,2 3,3 -> 2
5 1,1 2,1 3,1 4,1 5,0 5,1 -> 4


답변

젤리, 30 29 27 25 바이트

_AṢæ..
0,0ṭṚç2\+\<S
Œ!ç€Ṁ

온라인으로 사용해보십시오!

분명히 Jelly의 내적은 목록 크기 불일치를 무시하고 다른 배열의 추가 요소를 곱하지 않고 추가합니다. 2 바이트를 제거합니다.

설명

_AṢæ..              Helper link to calculate distance. Arguments: a, b
_                     subtract the vertices from each other
 A                    take absolute values of axes
  Ṣ                   sort the axes
   æ..                dot product with [0.5]

0,0ṭṚç2\+\<S        Helper link to calculate max cities. Arguments: perm, max
0,0                   create pair [0,0]
   ṭ                  append that to the permutation
    Ṛ                 reverse the permutation (gets the [0,0] to the beginning)
     ç2\              find distances of each pair using the previous link
        +\            find all partial sums
          <           see if each sum was less than the max
           S          sum to count cases where it was

Œ!ç€Ṁ               Main link. Arguments: cities, max
Œ!                    get permutations of cities
  ç€                  find max cities for each permutation using the previous link
    Ṁ                 take the maximum

답변

자바 7, 206 201 바이트

5 바이트를 절약 한 @KevinCruijssen에게 감사합니다

int f(float e,int[]a,int[]b){int x=0,y=0,c=0,d=0,t;float s;for(int i:a){s=(i!=x&b[c]==y)|(i==x&b[c]!=y)?Math.sqrt((t=i-x)*t+(t=b[c]-y)*t)*1:Math.abs(i-x)*1.5;d+=e-s>=0?1:0;e-=s;x=i;y=b[c++];}return d;}

언 골프

class Travellingpumpkin {

public static void main(String[] args) {

    System.out.println(f( 5 ,new int[] { 1,2,3,4,5,5 } , new int[] { 1,1,1,1,0,1 } ));

}
static int f( double e , int[]a , int[]b ) {
    int x = 0 , y = 0 , c = 0 , d = 0 , t;
    double s ;

    for ( int i : a ) {
    s = ( i != x & b[c] == y )|( i == x & b[c] != y )
         ? Math.sqrt( ( t = i - x ) * t + ( t = b[c] - y ) * t ) * 1
         : Math.abs( i - x ) * 1.5 ;


        d += e-s >= 0 ? 1 : 0 ;
        e -= s ;
        x = i ; y = b [ c++ ] ;
    }
    return d ;

}

   }

답변

스칼라, 196 바이트

def f(l:Int,c:(Int,Int)*)=c.permutations.map(x=>((0,0)+:x sliding 2 map{p=>val Seq(c,d)=Seq((p(0)._1-p(1)._1)abs,(p(0)._2-p(1)._2)abs).sorted
c*1.5+(d-c)}scanLeft 0d)(_+_)takeWhile(_<l)size).max-1

언 골프 드 :

def g (l: Int, c: (Int, Int)*) = {
    c.permutations
    .map { x =>
        ((0, 0) +: x).sliding(2).map({ p =>
            val Seq(c, d) = Seq((p(0)._1 - p(1)._1) abs, (p(0)._2 - p(1)._2) abs).sorted
            c * 1.5 + (d - c)
        }).scanLeft(0d)(_ + _).takeWhile(_ < l).size
    }.max - 1
}

설명 :

def f(l:Int,c:(Int,Int)*)= //defien a function with an int and a vararg-int-pait parameter
  c.permutations           //get the permutations of c, that is all possible routes
  .map(x=>                 //map each of them to...
    ((0,0)+:x                //prepend (0,0)
    sliding 2                //convert to a sequence of consecutive elemtens
    map{p=>                  //and map each of them to their distance:
      val Seq(c,d)=Seq(        //create a sequence of
        (p(0)._1-p(1)._1)abs,  //of the absolute distance between the x points
        (p(0)._2-p(1)._2)abs   //and he absolute distance between the y coordinates
      ).sorted                 //sort them and assign the smaller one to c and the larger one to d
      c*1.5+(d-c)              //we do the minimum difference diagonally
    }                        //we now have a sequence of sequence of the distances for each route
    scanLeft 0d)(_+_)       //calculate the cumulative sum
    takeWhile(_<l)          //and drop all elements that are larger than the candle lifespan
    size                    //take the size
  ).max-1                   //take the maximum, taht is the size of the largest route and subtract 1 because we added (0,0) at the beginning

답변

자바 스크립트 (ES6), 145

익명 재귀 함수, 매개 변수 s는 촛불 수명, 매개 변수 l는 마을 좌표 목록입니다.

깊이 우선 검색 , 정지 거리가 촛불 수명을 reachs 때

f=(s,l,x=0,y=0,v=0,A=Math.abs,X=Math.max)=>X(v,...l.map(([t,u],i,[h,...l],q=A(t-x),p=A(u-y),d=(l[i-1]=h,p+q+X(p,q))/2)=>s<=d?v:f(s-d,l,t,u,1+v)))

덜 골프 아래 스 니펫을 참조하십시오

테스트

f=(s,l,x=0,y=0,v=0,A=Math.abs,X=Math.max)=>
  X(v,...l.map(
      ([t,u],i,[h,...l],q=A(t-x),p=A(u-y),d=(l[i-1]=h,p+q+X(p,q))/2)=>
      s<=d?v:f(s-d,l,t,u,1+v)
  ))

// ungolfed version

F=(s, l,
   x=0, y=0, // current position
   v=0 // current number of visited sites 
  ) =>
   Math.max(v, ...l.map(
     (
       [t,u], i, [h,...l], // lambda arguments
       q = Math.abs(t-x), p = Math.abs(u-y), // locals
       d = (p+q+Math.max(p,q))/2
     ) => (
       l[i-1] = h,
       s <= d
         ? v
         : F(s-d, l, t, u, v+1)
     )
  ))

;[[4,[[-1,0],[1,0],[2,0],[3,0],[4,0],[5,0]], 3]
,[4, [[1,1],[2,2],[3,3]], 2]
,[5, [[1,1],[2,1],[3,1],[4,1],[5,0],[5,1]], 4]
].forEach(test=>{
  var span=test[0],list=test[1],check=test[2],
      result = f(span, list)
  console.log(result==check?'OK':'KO',span, list+'', result)
})

답변

MATL , 27 바이트

EH:"iY@OwYc!d|]yyXl++Ys>sX>

편집 (2016 년 11 월 26 일) : Xl기능 이 변경되었으므로 위 코드에서로 대체해야합니다 2$X>. 아래 링크에는 해당 수정 사항이 포함되어 있습니다.

온라인으로 사용해보십시오! 또는 모든 테스트 사례를 확인하십시오 .

설명

각 좌표에서 ΔxΔy 로 분리 된 두 도시 사이 의 호박 거리는 (| Δ x | + | Δ y | + max (| Δ x |, | Δ y |)) / 2로 얻을 수 있습니다.

코드는 다음 단계를 따릅니다.

  1. x 좌표와 y 좌표 의 모든 순열을 생성하고 각 0 앞에 a를 붙입니다. 각 순열은 가능한 경로를 나타냅니다.
  2. 각 경로에 대한 절대 연속 차를 계산합니다 (위의 | Δ x | 및 | Δ y |).
  3. 각 경로의 각 단계에 대한 호박 거리를 구하십시오.
  4. 각 경로의 누적 거리 합계를 계산합니다.
  5. 각 경로에 대해 누적 된 거리가 chandle 수명에 도달하기 전에 걸음 수를 찾으십시오.
  6. 위의 최대 값을 가져옵니다.

주석이 달린 코드 :

E        % Input candle lifespan implicitly. Multiply by 2
H:"      % Do thie twice
  i      %   Input array of x or y coordinates
  Y@     %   All permutations. Gives a matrix, with each permutation in a row
  OwYc   %   Prepend a 0 to each row
  !      %   Transpose
  d|     %   Consecutive differences along each column. Absolute value
]        % End
yy       % Duplicate the two matrices (x and y coordinates of all paths)
Xl       % Take maximum between the two, element-wise
++       % Add twice. This gives twice the pumpkin distance
Ys       % Cumulative sum along each column
>        % True for cumulative sums that exceed twice the candle lifespan
s        % Sum of true values for each column
X>       % Maximum of the resulting row array. Inmplicitly display

답변

파이썬 2.7 , 422 바이트

추가 개선 사항을 지적한 NoOneIsHere에 감사합니다!

목록을 저장하지 않고 반복자를 대신 사용하는 것에 대해 edc65에게 감사드립니다!

온라인으로 사용해보십시오!

from itertools import permutations
def d(s,e):
    d=0
    while s!=e:
        x=1 if s[0]<e[0] else -1 if s[0]>e[0] else 0
        y=1 if s[1]<e[1] else -1 if s[1]>e[1] else 0
        s=(s[0]+x,s[1]+y)
        d+=(1,1.5)[x and y]
return d
l,m=4,0
for o in permutations([(1,1),(2,2),(3,3)]):
    a,c=l-d((0,0),o[0]),1
    for j in range(len(o)-1):
        a-=d(o[j],o[j+1])
        c+=(0,1)[a>0]
    m=max(c,m)
print m

설명:

이 함수는 주어진 규칙에 따라 두 점 사이의 거리를 계산하고 루프는 입력 생성기에 의해 생성 된 모든 순열을 반복하고 거리가 양초 수명보다 짧으면 빼고 장소를 추가합니다. counter, 해당 카운터가 현재 최대 값보다 크면이를 대체합니다.

언 골프 :

from itertools import permutations

def distance(start_pos, end_pos):
    distance = 0
    while start_pos != end_pos:
        mod_x = 1 if start_pos[0] < end_pos[0] else -1 if start_pos[0] > end_pos[0] else 0
        mod_y = 1 if start_pos[1] < end_pos[1] else -1 if start_pos[1] > end_pos[1] else 0
        start_pos = (start_pos[0] + mod_x, start_pos[1] + mod_y)
        distance += (1, 1.5)[mod_x and mod_y]
    return distance

lifespan, max_amount = 4, 0
for item in permutations([(1,1), (2,2), (3,3)]):
    lifespan_local, current = lifespan - distance((0,0), item[0]), 1
    for j in range(len(item) - 1):
        lifespan_local -= distance(item[j], item[j + 1])
        current += (0, 1)[lifespan_local > 0]
    max_amount = max(current, max_amount)
print max_amount

답변

PHP, 309 바이트

function j($x,$y,$c,$v){if($s=array_search([$x,$y],$v))unset($v[$s]);for($c--,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,0,-1,0][$i],$y+[0,1,0,-1][$i],$c,$v))>$m?$n:$m;for($c-=.5,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,-1,-1,1][$i],$y+[1,1,-1,-1][$i],$c,$v))>$m?$n:$m;return$s?++$m:$m;}echo j(0,0,$argv[1],array_chunk($argv,2));

절대적으로 무차별적인 힘과 아주 짧지는 않습니다. 다음과 같이 사용하십시오.

php -r "function j($x,$y,$c,$v){if($s=array_search([$x,$y],$v))unset($v[$s]);for($c--,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,0,-1,0][$i],$y+[0,1,0,-1][$i],$c,$v))>$m?$n:$m;for($c-=.5,$i=4;$c>0&&$i--;)$m=($n=j($x+[1,-1,-1,1][$i],$y+[1,1,-1,-1][$i],$c,$v))>$m?$n:$m;return$s?++$m:$m;}echo j(0,0,$argv[1],array_chunk($argv,2));" 5 1 1 2 1 3 1 4 1 5 0 5 1

더 많은 공백이 있고 파일에 저장되었습니다.

<?php
function j( $x, $y, $c, $v)
{
    if( $s = array_search( [$x,$y], $v ) )
        unset( $v[$s] );

    for( $c--, $i=4; $c>0 && $i--;)
        $m = ( $n=j($x+[1,0,-1,0][$i],$y+[0,1,0,-1][$i],$c,$v) )>$m ? $n : $m;

    for( $c-=.5, $i=4; $c>0 && $i--;)
        $m = ( $n=j($x+[1,-1,-1,1][$i],$y+[1,1,-1,-1][$i],$c,$v) )>$m ? $n : $m;

    return $s ? ++$m : $m;
}
echo j( 0, 0, $argv[1], array_chunk($argv,2) );