주간 챌린지 #080 태스크 #2::라쿠

작업 #2 캔디 카운트



제출자: Mohammad S Anwar

@N 후보자의 순위가 제공됩니다.

모두에게 필요한 총 사탕을 찾는 스크립트를 작성하십시오.
후보자. 다음 규칙을 따라야 합니다.
a) 각 후보자에게 적어도 하나의 사탕을 주어야 합니다.
b) 순위가 더 높은 후보자는 양쪽에 있는 중재 이웃보다 더 많은 사탕을 얻습니다.

예 1:



Input: @N = (1, 2, 2)

설명:



Applying rule #a, each candidate will get one candy. 
So total candies needed so far 3.
 Now applying rule #b,  the first candidate do not get any more
candy as its rank is lower than it's neighbours.
  The second candidate gets one more candy as it's ranking is
higher than it's neighbour.
  Finally the third candidate do not get any extra candy
as it's ranking is not higher than neighbour.
  Therefore total candies required is 4.

Output: 4

예 2:



Input: @N = (1, 4, 3, 2)

Applying rule #a, each candidate will get one candy. So total candies needed so far 4.
  Now applying rule #b, the first candidate do not get any more candy as its rank is lower than it's neighbours.
The second candidate gets two more candies as it's ranking is
higher than it's both neighbour. The third candidate gets
one more candy as it's ranking is higher than it's neighbour.
  Finally the fourth candidate do not get any extra candy
as it's ranking is not higher than neighbour.
  Therefore total candies required is 7.

Output: 7

처음에는 설명을 보지 않으면 동그랗게 둘러앉아 있다고 생각하기 쉽습니다. 나란히 앉아 눈앞의 사탕을 바라보는 모습이 더 재미있었으면 좋겠다. :-]

그래서 나는 Raku
사탕 하나만 먹고 배고파지면
솔루션은 다음과 같이 보일 수 있습니다 ...

sub candies( *@nums where @nums.all ~~ UInt ) {
    @nums.elems.say;
}



> candies(1, 4, 3, 2);
4

하지만 우리는 인간.. 더 높은 순위를 가지면 더 많은 것을 얻습니다.
이웃의 순위를 보기 위해 rotor을 다시 사용했습니다.
그러나 각 첫 번째 요소와 마지막 요소에는 하나의 이웃만 있습니다.
옆에 안드로이드 이웃을 추가하면 아마 편리할 것입니다.
이 경우 "Inf"를 사용했으므로 Android는 절대 추가 사탕을 주지 않습니다.

sub MAIN( *@nums where @nums.all ~~ UInt ) {
    (Inf, |@nums, Inf).
    rotor(3=>-1).
    say;
}



raku test.raku 1 4 3 2 # example #2
((Inf 1 4) (1 4 3) (4 3 2) (3 2 Inf))

그래서 우리는 이웃과 비교할 때 우리가 어떻게 하나 또는 두 개의 사탕을 더 할 수 있는지 알 수 있습니다 (우리가 그들보다 100 더 높은 위치에있어 사람들이 게으르더라도)

sub MAIN( *@nums where @nums.all ~~ UInt ) {
    (Inf,|@nums,Inf).
    rotor(3=>-2).
    kv. # takes each elements as key => value
    map( -> $index, $grp {
              my $c = 1; # rule "a"
              if $grp[0] < $grp[1] {
                  ++$c;
              }
              if $grp[2] < $grp[1] {
                  ++$c;
              }
              "{$index} gets => $c as {$grp}"
           } ).
    join("\n").
    say;
}



0 gets => 1 as Inf 1 4
1 gets => 3 as 1 4 3
2 gets => 2 as 4 3 2
3 gets => 1 as 3 2 Inf

주어진 데이터를 확인하고 결과가 내가 얻고자 하는 것과 일치하는지 확인하는 것이 항상 좋은 습관이라고 생각합니다.
이제 우리는 그것들을 모두 하나의 요약 형식으로 추가할 수 있습니다.

그러나 우리가 그것이 올바른 방법이라고 생각한다면. 왜 더 짧게 만들지?
그래서 조금 컴팩트한(골프) 코드를 얻으려고 했습니다.

그리고 최종 형태는 ...

sub MAIN{(|@_,|((|@_,|@_.reverse).rotor(2=>-1).map({[-] $_}).grep(*>0))).elems.say}

앞서 언급했듯이. 저는 골프 프로그래머가 아닙니다.
그리고 놀랍게도 - 항상... 작업을 수행하는 더 짧은 방법이 있습니다.

좋은 웹페이지 즐겨찾기