text:
Is my Matrix Arrowhead?
Definition
An arrowhead matrix is a matrix that has all entries equal to 0, except the ones on the main diagonal, top row and leftmost column. In other words, the matrix should look like this:

* * * * * *
* * 0 0 0 0
* 0 * 0 0 0
* 0 0 * 0 0
* 0 0 0 * 0
* 0 0 0 0 *

Where each * is any non-zero entry.
Task
Given a square matrix of non-negative integers, check whether it is arrowhead according to the definition above.
You may not take the size of the matrix as input, unless your language’s equivalent to an array is something like a pointer and a length (like C). It will always be at least 3 x 3.
The shortest code in bytes in each language wins.
Input and Output
You can pick among any of the following formats for receiving input:

A matrix in the native matrix type (if your language has one)
A 2D array1 (an array of 1D arrays, each corresponding to one row)
A 1D array (since the matrix is always square)
A string (you chose the spacing, but please do not abuse this in any way).

When it comes to providing output, you can either report a truthy / falsy value following the standard decision-problem definition, or choose any two distinct and consistent values.
Moreover, you can take input and give output through any standard method, in any programming language, while taking note that these loopholes are forbidden by default. If want to pick any other format or are unsure about something, please ask in the comments.
1: or your language's equivalent (list, vector, etc.)
Examples
Let's look at the following examples:

1 2 2 2
2 1 0 0
3 0 1 0
4 0 0 1

This is an arrowhead matrix (your programs should report a truthy value), because the elements on the main diagonal are 1 1 1 1, those on the top row are 1 2 2 2 and those on the leftmost column are 1 2 3 4. All other entries are 0, so this satisfies all the conditions.

3 5 6
7 1 0
8 0 0

This matrix is not arrowhead because there is a 0 on the main diagonal.

9 9 9 9
9 9 0 0
9 7 9 0
9 0 0 9

This one is not arrowhead either, because it contains a 7 in place of a 0.
More test cases
Truthy:

[[1, 1, 1], [1, 1, 0], [1, 0, 1]]
[[1, 2, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]
[[1, 2, 2, 2], [2, 1, 0, 0], [3, 0, 1, 0], [4, 0, 0, 1]]
[[34, 11, 35, 5], [56, 567, 0, 0], [58, 0, 679, 0], [40, 0, 0, 7]]

Falsy:

[[3, 5, 6], [7, 1, 0], [8, 0, 0]]
[[9, 9, 9, 9], [9, 9, 0, 0], [9, 7, 9, 0], [9, 0, 0, 9]]
[[1, 0, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]
[[1, 6, 3, 4], [13, 2, 0, 6], [29, 0, 1, 0], [2, 0, 0, 4]]

Is it possible that the matrix can contain negative numbers

@Zacharý No you may assume they are all non-negative.

Pedant: A two dimensional array and a matrix are not the same thing, nor is it the same as an array of arrays. Is input as a two dimensional array acceptable if your language of choice is civilised enough to support multidimensional arrays?

@IanBush Yes, a 2D array is totally fine.

Can we take the input as a 1D matrix, and an int determining the size, or must we determine the size ourselves?

@FlipTack You must determine the size yourself. Clarified in the post.

@Mr.Xcoder This would be a sufficiently different and interesting challenge if the arrowhead could point in any direction

@dylnan Feel free to post it m, if you want.

In languages such as C, may we have the length? Otherwise the easiest (only?) way to check the length of the 2D array is to spawn a thread, get it to try to seek past the end of the end and hope it segfaults at the right place.

@wizzwizz4 Yes, for langs like C. or your language's equivalent implies that, since the equivalent in C is a pointer and a length, although You may not take the size of the matrix as input kind of contradicts that. Will clarify.

Javascript (ES6), 48 47 bytes
Saved 1 byte thanks to edc65
m=>m.some((r,y)=>r.some((c,x)=>(x*y&&x!=y)^!c))

Returns false for arrowhead matrices and true for non-arrowhead matrices (allowed since any two distinct values can be used to represent true and false)
Test cases:

f=m=>m.some((r,y)=>r.some((c,x)=>(x*y&&x!=y)^!c))
console.log(f([[1, 1, 1], [1, 1, 0], [1, 0, 1]]))
console.log(f([[1, 2, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(f([[1, 2, 2, 2], [2, 1, 0, 0], [3, 0, 1, 0], [4, 0, 0, 1]]))
console.log(f([[34, 11, 35, 5], [56, 567, 0, 0], [58, 0, 679, 0], [40, 0, 0, 7]]))
console.log(f([[3, 5, 6], [7, 1, 0], [8, 0, 0]]))
console.log(f([[9, 9, 9, 9], [9, 9, 0, 0], [9, 7, 9, 0], [9, 0, 0, 9]]))
console.log(f([[1, 0, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(f([[1, 6, 3, 4], [13, 2, 0, 6], [29, 0, 1, 0], [2, 0, 0, 4]]))

Now that's a truly clever approach!

could this work ? f=m=>m.some((r,y)=>r.some((c,x)=>(x*y&&x!=y)^!c))

@edc65 Without the f= of course ;-)

J, 21 20 19 17 15 bytes
-4 bytes thanks to @GalenIvanov.
*-:1,1,.=&/:@}.

Takes input as a matrix (rank 2 array).
Try it online!
Explanation
Let the edit history be a lesson to you not to golf and write an explanation at the same time.
* -: 1, 1,. = & /: @ }.  Let m be the input matrix.
            = & /: @ }.  Identity matrix 1 smaller than m.
                     }.    Behead (m without its first row).
                   @       Composed with.
                /:         Grade up (get len(m) - 1 unique elements)
              &            Composed with.
            =              Self-classify (compare equality with
                           unique elements)
        1,.              Prepend a column of 1s
     1,                  Prepend a row of 1s
*                        Signum (0 becomes 0, n > 0 becomes 1)
  -:                     Does it match the generated arrowhead matrix?

Visual explanation
Note that this is done on the REPL (inputs are given starting with three spaces and output are given without any leading spaces). Because of that, I sometimes omit composition functions like @ and & since things on the REPL are evaluated right-to-left (functions are more complex).
Suppose you have the following sample matrix:
   ] m =. 4 4 $ 1 2 3 4 1 1 0 0 1 0 1 0 1 0 0 1
1 2 3 4
1 1 0 0
1 0 1 0
1 0 0 1

First, I'd like to explain (and give a shoutout to) @GalenIvanov's very clever way of generating the identity matrix, which is the following =&/:@}..
First, we behead the input matrix (}.).
   }. m
1 1 0 0
1 0 1 0
1 0 0 1

Then we get the indices each row would be in were the rows sorted using /:-grade up.
   /: }. m
2 1 0

Note that the resulting indices are unique: the list has no duplicate elements (and why would it? There's no way to place two elements in the same position in an array).
Finally, we use the niche but helpful =-self-classify. This monad compares each unique element to all of the other elements in an array. Remember how I mentioned it was important that the resulting indicies are unique? Since =-self-classify does the comparisons in the order that the unique elements appear in the list, the resulting output will be the identity matrix for a unique input (this is why =@i. is how you can make an identity matrix of a given length).
   = /: }. m
1 0 0
0 1 0
0 0 1
   NB. This is what is happening
   (2 = 2 1 0) , (1 = 2 1 0) ,: (0 = 2 1 0)
1 0 0
0 1 0
0 0 1

Once we have the identity matrix, it's a matter of adding a row of ones and a column of ones, which is done very simply (if given an atom - i.e. a single element - the , family will repeat it to fill when it's being added):
   1,. (=&/:@}. m)
1 1 0 0
1 0 1 0
1 0 0 1
   1, (1,. =&/:@}. m)
1 1 1 1
1 1 0 0
1 0 1 0
1 0 0 1

Then we simply compare the generated arrowhead matrix to the signum of the input matrix.
   * m
1 1 1 1
1 1 0 0
1 0 1 0
1 0 0 1
   (* m) -: (1, 1,. =&/:@}. m)
1

Isn't * enough instead of 0@< (for 17 bytes)?
Try it

@GalenIvanov good catch, I think so. Thanks! Time to re-edit the explanation lol.

I think I found a new way to generate the identity matrix: =&/: When I combined it with }.,  I got this *-:1,1,.=&/:@}. for 15 bytes
Try it online!

@GalenIvanov brilliant approach (both the use of /:-grade and }.-behead), thank you again! I'll edit it in.

Hmm, in fact *-:1,1,.=@}. works just fine - no need of fancy way to find the identity matrix. You can generate an identity matrix from the square matrix itself simply by =. So drop one row with }., make the identity matrix with = , add a row and a  column with 1 and so on.

@GalenIvanov does this work if there are duplicate rows in the matrix?

You are right, it doesn't work for duplicate rows

Nice.  Another 15 byte variation: *-:${.1,1,.=@/:

APL (Dyalog Classic), 19 16 15 13 bytes
-1 byte thanks to @ErikTheOutgolfer
(⎕IO←0)
×≡(∧=⌊)/¨∘⍳∘⍴

Try it online!
-2 bytes thanks to @ngn and @H.PWiz
How?
(2D input matrix S)

×≡ Check whether S is positive only on ...
(∧=⌊ ... the diagonals or the top row and left column ...
)/¨∘⍳∘⍴ ... of S.

nice utilization of ⍳∘⍴ for cartesian product.

×≡(=/∨1∊⊢)¨∘⍳∘⍴

(=/∨1∊⊢) -> (~≠⌊⌊)/

@ngn Even better: (∧=⌊)/, of course both require ⎕IO←0

Wolfram Language (Mathematica), 47 bytes
Clip@#==Array[If[1<#!=#2>1,0,1]&,{1,1}Tr[1^#]]&

Try it online!
Explanation: Clip@# replaces all the non-zero numbers in the matrix with 1s, then we compare this to an array with dimensions {1,1}Tr[1^#] = {Length@#, Length@#} with 0 in position i,j when 1 < i != j > 1, and 1 otherwise.
(Roughly based on Uriel's answer.)
Here's another idea that's 16 bytes longer — feel free to steal it if you can golf it down:
Union@@Array[{1,#}~Tuples~2&,Length@#]==Most@Keys@ArrayRules@#&

Try it online!

APL (Dyalog), 21 18 17 bytes
×≡1⍪1,(=/¨∘⍳1-⍨⍴)

Try it online!
How?
This one goes the other way -
=/¨∘⍳ - creates the identity matrix
1-⍨⍴ - for n - 1
1⍪1, - prepends a column and a row of 1s
≡ - compares with
× - the original matrix, after it has gone an element-wise signum-ing

PowerShell, 112 108 bytes
param($a)$o=+!(0-in$a[0]);1..($x=$a.count-1)|%{$i=$_;0..$x|%{$o*=(!($y=$a[$i][$_]),$y)[!$_-or$_-eq$i]}};!!$o

Try it online!
Takes input and manipulates as an array-of-arrays, since PowerShell doesn't support matrices (outside of the .NET Direct3D transform matrices support, which is something entirely different).
The whole algorithm is based on the fact that non-zero numbers are truthy and zero is falsey in PowerShell, and using multiplication to determine those truthy/falsey values.
We first take the first row, $a[0], and check whether 0 is -in that array, store that into our $output variable. If anything in that row is zero, then the $o is also zero, otherwise it's one, done by a quick cast-to-int with +.
Next we loop from 1 up to $a.count-1, setting $x along the way -- we're going to be looping through each row one at a time.
Each iteration we set helper variable $i to keep track of what row we're on, then loop from 0 to $x to iterate each element in this row. Inside the inner loop, we're again multiplying $o, this time by selecting from a tuple setup as a pseudo-ternary operator.
The tuple's conditional, !$_-or$_-eq$i, says "when we're on the 0th column, or the column matches the row (i.e., the main diagonal)" to select the second half of the tuple when truthy or the first half when falsey. The tuple is composed of !($y=$a[$i][$_]), $y. The first half sets $y for golfing the second half, but either way we're selecting the current element. The first half does Boolean negation on it, while the second half just takes the element as-is. Thus, if we're not on the 0th column nor the main diagonal, we ensure that the element is zero by taking the Boolean-not of it. Similarly, we ensure the 0th column or main diagonal is non-zero by simply taking it.
So now that we've iterated through every element in the matrix, $o is either going to be 0 if some element was incorrect, or some non-zero integer if it is an arrowhead matrix. We double-Boolean-not that to get either False or True respectively, to make our output consistent, and that's left on the pipeline where printing is implicit.

+ = [int]? That is nice.

@root One of the PowerShell tips.

Jelly, 14 12 bytes
ŒDµḢ;Ḣ€Ȧ>FẸ$

-2 bytes from Pietu1998
Try it online!
Explanation
[[9,7,1],
 [7,1,0],
 [7,0,1]]

Use the above matrix as an example input.
ŒDµḢ;Ḣ€Ȧ>FẸ$
ŒD              Diagonals → [[9, 1, 1], [7, 0], [1], [7], [7, 0]]
  µ             New monadic link
   Ḣ            Head → [9, 1, 1]. Alters diagonals list.
    ;Ḣ€         Append with the head of each of the other diagonals → [9, 1, 1, 7, 1, 7, 7]
       Ȧ        Logical all → 1
         FẸ$    Flatten what's left in diagonals then take logical any → [[0],[],[],[0]] → [0,0] → 0
        >       Matrix is an arrowhead iff result of Ȧ > result of Ẹ

@wizzwizz4 I'm not sure what you mean

@wizzwizz4 this code shows how the elements of the matrix are regrouped. It does take the top, left and main diagonal. Is this what you meant?

I meant the actual visual representation of the code that you provided in your explanation. I was trying to be funny but it obviously didn't work. I'll clean up these comments.

MATL, 15 bytes
gtZyXy,!llY(]X=

Input is a matrix (using ; as row separator). Output is 1 for arrowhead, 0 otherwise.
Try it online! Or verify all test cases.
Explanation
g        % Implicit input. Convert to logical values (nonzero becomes true and
         % zero becomes false)
t        % Duplicate
Zy       % Size
Xy       % Identity matrix of that size
,        % Do twice
  !      %   Transpose
  ll     %   Push 1 twice
  Y(     %   Write 1 at all entries of row 1
]        % End
X=       % Are the two matrices (input and constructed) equal? Implicit display

What exactly is Indeity matrix?

@EriktheOutgolfer obviously a matrix containing a deity.

@cole perhaps related to a matrix over the Elysian field

R, 78 70 69 68 54 53 bytes
function(m){d=diag(nrow(m))
d[1,]=d[,1]=1
all(d!=!m)}

Try it online!
Porting Luis Mendo's answer is much shorter than my former approach.
Thanks to rturnbull for pointing out a bug, and golfing down a byte!
old answer, 68 bytes:
function(m,i=which(!m,T))all(i[,1]-i[,2],i!=1,sum(m>0)==3*nrow(m)-2)

Try it online!
duckmayr's answer tests that all entries on the main diagonal and first row/column (m[i]) are nonzero and the rest (m[-i]) are zero, using some nice arithmetic to get the diagonal and the first row.
This answer, however, tests to make sure that (1) zero entries are not on the main diagonal or the first row/column, and (2) that there are, given an n x n matrix, 3*n-2 nonzero entries.
which returns the indices where its input is TRUE, and with the optional arr.ind=T, returns an array of indices for each array dimension, in this case, two.
Hence when any(i[,1]==i[,2]), there exists a zero on the diagonal, and when any(i==1), there exists a zero in the first row or the first column.
Finally, a little arithmetic shows that the number of nonzero entries must be 3*n-2, n from the first column, n-1 from the diagonal, and n-1 from the first row.

This doesn't seem to work for arrow matrices where the values are not 1. Did you mean all(!m==!d) in the last line?

@rturnbull ah! Thank you. R operator syntax is so weird. I really meant (!!m)==d but ! has lower precedence than ==. I think d==!!m should do the trick, though.

It looks like d!=!m does the same, for one byte less. You can save another byte by using pryr::f syntax rather than function too.

I tried to golf it but the best i can do is still 53.

@JayCe nah both your answer and mine can be golfed to 52, and I'm not sure why it didn't occur to me before... I'd post yours as separate; the one-line approach is quite nice and I suspect there may be some more room for improvement in yours

hum... all(d-!m)?

@JayCe got it in one shot!

!sd(d+!m) brings it down to 52 as well.

Python 2, 75 bytes
lambda m,E=enumerate:all((x[j]>0)-(i>0<j!=i)for i,x in E(m)for j,y in E(m))

Try it online!
Python 2, 85 bytes
Taking the array as a 1D matrix:
def f(m):s=len(m)**.5;print all((v<1)^(0in(p>s,p%s,p//s-p%s))for p,v in enumerate(m))

Try it online!

Did you mean "1D matrix" in the top solution?

@NikoNyrh oops, fixed

C (gcc), 80 75 69 bytes
i;f(A,n)int*A;{for(i=0;i<n*n;)n*=A[i]<1^(i<n|i%n<1|i/n==i++%n);n=!n;}

Try it online!
Saved 5 bytes thanks to scottinet! And 6 more thanks to ceilingcat!
Reused the test code from this answer.
Linearly scans the array for any incorrect values, returning 0 for an arrowhead matrix and 1 otherwise. We check by computing the exclusive or of whether the item at a given position is zero and whether that position is on the arrow.
Encoding the information of the 2D array into one dimension leads to a fairly simple set of conditions. If we let i be our 0-based index into the n dimensional array, then i<n describes the first row. Similarly, i%n==0 describes the first column and i/n==i%n describes the diagonal.
The best trick I found for handling the return is to set the dimension to zero when encountering an error. This causes the loop to terminate immediately, then returning the logical negation of the dimension will give us one of two distinct values. scottinet found the way to make GCC return it more nicely.

-2 bytes with some more golfing

and an additional -4 bytes by abusing gcc's way of returning values

@scottinet Thanks! I was having trouble figuring out which value I should set to use that trick.

Actually, I don't believe your first golf works. It passed the test cases because there was never a zero in the first position. Added a case and reverted that change.

int test0[] = {0, 1, 1, 1, 1, 0, 1, 0, 1};
printf("%d\n", f(test0, 3));
Has to return 0 not 1 (if is the 3x3 matrx 011 110 101) because a[0,0] is 0

@RosLuP The function returns 0 for an arrowhead matrix, and 1 for a non-arrowhead matrix. I do not believe there is a problem, in this case.

@ceilingcat Thanks! Good catches on bitwise OR being better with no precedence problems, changing the test to multiply, and moving the increment out.

Python 3, 72 71 bytes
lambda x,e=enumerate:any(0**n^(0<i!=j>0)for i,r in e(x)for j,n in e(r))

Thanks to @xnor for golfing off 1 byte!
Try it online!

I think 0<i!=j>0 saves a byte,

@xnor Thanks! I don't think I've ever re-used a number in a comparison chain...

Python 2, 92 90 bytes
def f(m):l=len(m);return all((m[a%l][a/l]<1)^any([a<l,a%l<1,a/l==a%l])for a in range(l*l))

Try it online!
Credits

Reduced from 92 bytes to 90 by Mr. Xcoder

Haskell, 62 bytes
-3 bytes thanks to Mr. Xcoder. -13 bytes thanks to user28667. -5 bytes thanks to Zgarb.
z=zip[0..]
f m=and[(i==j||i*j<1)==(a>0)|(i,r)<-z m,(j,a)<-z r]

Try it online!

80 bytes.... You almost always forget about <1 and such tricks? :P

(x==y||x==0||y==0)==(m!!y!!x/=0) should be shorter

62 bytes by zipping instead of indexing, and doing x*y<1.

Jelly, 10 bytes
ŒDµḢṠQṭT€E

Try it online!

Clojure, 128 95 92 85 bytes
#(every? neg?(for[R[(range(count %))]i R j R]((if((set[i(- i j)j])0)- dec)((% i)j))))

It is always exciting to see two consecutive opening brackets.
Original version:
#(and(apply =(map assoc(for[i(rest %)](subvec i 1))(range)(repeat 0)))(every? pos?(concat(map nth %(range))(% 0)(map first %))))

The first part works by associng diagonal elements of the sub-matrix to zero, and checking that all rows are equal :) I used a similar trick at Jacobian method.
Latter part concatenates the diagonal + first row and column and checks that they are positive.

APL+WIN, 36 33 bytes
(↑⍴m)=+/(+⌿m)=+/m←×m×n∘.×n←⍳↑⍴m←⎕

Prompts for screen input of an APL 2d matrix.

Clojure, 212 206 188 bytes
-6 bytes by removing some missed spaces, and shortcutting range. I might have to let this sit so I can think of a better way.
-18 bytes thanks to @NikoNyrh, and creating shortcuts for map.
(fn[m](let[r range a map z zero?](and(every? #(not(z %))(concat(m 0)(rest(a #(% 0)m))(a get m(r))))(every? z(apply concat(into(a #(take(dec %)%2)(r)(a rest m))(a take-last(r)(reverse(rest m)))))))))

Awful, just awful. I don't know why I can't wrap my head around a reasonable solution.
Takes a nested vector as input.
(defn arrowhead? [matrix]
  (let [; Get the 0th cell of the 0th row, then the 1st cell of the 1st row...
        main-diagonal (map get matrix (range))

        ; Get the 0th cell of each row
        first-col (rest (map #(% 0) matrix))
        arrowhead (concat (matrix 0) first-col main-diagonal)

        ;
        right-rest (map take-last (range) (reverse (rest matrix)))
        left-rest (map #(take (dec %) %2) (range) (map rest matrix))
        rest-matrix (apply concat (into left-rest right-rest))]

    ; And check them
    (and (every? pos? %) arrowhead
         (every? zero? rest-matrix))))

I tried rewriting this from scratch using a different method, and it ended up longer. Instead of manually carving out the "rest" sections of the matrix, I instead decided to try generating all the coordinates in the matrix, generating the coordinates of the arrowhead, then use clojure.set/difference to get the non-arrowhead cells. Unfortunately, the call to that built-in is costly:
223 bytes
(fn[m](let[l(range(count m))g #(get-in m(reverse %))e every? a(for[y l x l][x y])k #(map % l)r(concat(k #(do[% %]))(k #(do[0%]))(k #(do[% 0])))](and(e #(zero?(g %))(clojure.set/difference(set a)(set r)))(e #(pos?(g %)))r)))

(defn arrowhead? [matrix]
  (let [length-range (range (count matrix))
        get-cell #(get-in matrix (reverse %))
        all-coords (for [y length-range
                         x length-range]
                     [x y])

        k #(map % length-range)

        diag (k #(do[% %]))
        top-side (k #(do [0 %]))
        left-side (k #(do [% 0]))
        arrowhead (concat diag top-side left-side)

                   ; 22 bytes! Ouch
        rest-cells (clojure.set/difference (set all-coords) (set arrowhead))]

    (and (every? #(zero? (get-cell %)) rest-cells)
         (every? #(pos? (get-cell %)) arrowhead))))

There is quite lot of room for improvement, for example #(drop 1 %) is same as rest and #(not(zero? %)) is same as pos? (as we have non-negative numbers). You might want to have a look at my 128-byte answer, which has similar approacha s this one. After implementing that I realized that it is a lot shorted to deal with index-based access in a for-loop.

@NikoNyrh Ya, I wasn't in a very good groove that day. I don't know how I forgot about rest. I should probably just scrap this attempt and try again.

Pyth, 22 21 bytes
This is definitely not the language for matrix manipulation.
.As.e+!MWk.Db,0k,@bkh

For each row b and its index k in the matrix (.e), grabs the first and kth entries (left side and diagonal) with ,@bkh and (+) all the other entries with .Db,0k. If k isn't 0 to correspond to the first row (Wk), then !not M all of those entries.  Once all of those have been selected, make sure  all of them are true. (.As)  If there's a 0 where there shouldn't be, then the corresponding location will be grabbed as is and mess up the and, and if there's a nonzero where there shouldn't be, it'll be ! notted to 0, which is also false.
Test suite.
-1 bytes for swapping the orders around.

Wow this solution is really nice given that Pyth is quite parallel with matrix manipulation. Probably up for another Pyth duel tomorrow :P

You might be able to shorten this using either @VQUQ or .DVQUQ  For diagonals / deleting diagonals. But that would require a completely different approach. Not sure though... (BTW forgot to update link?)

@Mr.Xcoder Fixed link, I'll try to mess around with other strategies tomorrow.

I arrived at an alternative 21-byter using my VQUQ idea: >.A++hCQhQ.(VQUQsstCt. This seems highly redundant, though. You might be able to tweak it in order to save a few bytes.

Pip, 31 23 22 bytes
{0<_!=B>0MC#a==0=_MMa}

This is a function that takes a 2D nested list of numbers. Try it online!
Explanation
A whole lot of comparisons going on here. The first thing to know is that comparison operators in Pip can be chained together, like in Python: 5>4>3 is 5>4 and 4>3 (true), not (5>4)>3 (false). The second is that this doesn't apply to ==, the "exactly equals" operator. Another difference: regular comparisons have higher precedence than the mapping operators MC and MM and can be used in lambda expressions, while == has lower precedence and can't.
{                    }  Define a function with argument a:
 0<_!=B>0MC#a            Generate a matrix (as nested lists) that has 0 on the first row,
                          first column, and main diagonal, and 1 elsewhere (see below for
                          details)
               0=_MMa    Map the function 0=_ to the elements of the elements of a,
                          generating a matrix that is 0 where a is nonzero and vice versa
             ==          Test if the two matrices are equal, returning 0 or 1 accordingly

To generate the first matrix, we use MC, "map-coords." This operator takes a number, generates a square coordinate grid of that size, and maps a function to each (x,y) coordinate pair, returning a list of lists of the results. For example, {a+b} MC 3 would give the result [[0; 1; 2]; [1; 2; 3]; [2; 3; 4]].
Here, the size of the grid is #a, the size of our original argument. The function is 0<_!=B>0, which is a shorter way of writing {0 < a != b > 0}:
{        }  Function; a and b are the arguments (in our case, row and column)
 0<a        Return 1 (truthy) if a is greater than 0
    !=b     and a is not equal to b
       >0   and b is greater than 0

This returns 0 for the first row/column and the main diagonal, and 1 elsewhere.

Husk, 12 11 10 bytes
≡¹´Ṫ§^*=ŀL

Try it online!
Explanation
≡¹´Ṫ§^*=ŀL  Input is a k×k array A.
         L  The length, k.
        ŀ   The range [0,1..k-1].
  ´Ṫ        Outer product with itself by this function:
             Arguments are two numbers x and y.
       =     Equality of x and y
    §^       to the power of
      *      x times y.
≡¹          Does the result have the same shape and distribution of truthy values as A?

The idea is that Husk defines 0 to the power of 0 as 1, so the outer product has 1s on the first row and column.
Also, 1 to the power of any number is 1, so the outer product has 1s on the diagonal.
Other entries are 0 to the power of some positive number, which is 0.
This gives a binary arrowhead matrix, which we compare to the input with ≡.

Javascript (ES6), 58 bytes
My solution for Javascript:
m=>m.some((r,i)=>m[0][i]*r[0]*r[i]==0|r.filter(c=>i*c)[2])

Not as clever as Herman's answer, but I just felt like I should post it here too.

isArrowHead=m=>m.some((r,i)=>m[0][i]*r[0]*r[i]==0|r.filter(c=>i*c)[2])

console.log("-----should be false-----")

console.log(isArrowHead([[1, 1, 1], [1, 1, 0], [1, 0, 1]]))
console.log(isArrowHead([[1, 2, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(isArrowHead([[1, 2, 2, 2], [2, 1, 0, 0], [3, 0, 1, 0], [4, 0, 0, 1]]))
console.log(isArrowHead([[34, 11, 35, 5], [56, 567, 0, 0], [58, 0, 679, 0], [40, 0, 0, 7]]))

console.log("-----should be true-----")

console.log(isArrowHead([[3, 5, 6], [7, 1, 0], [8, 0, 0]]))
console.log(isArrowHead([[9, 9, 9, 9], [9, 9, 0, 0], [9, 7, 9, 0], [9, 0, 0, 9]]))
console.log(isArrowHead([[1, 0, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(isArrowHead([[1, 6, 3, 4], [13, 2, 0, 6], [29, 0, 1, 0], [2, 0, 0, 4]]))

console.log("-----end-----")

Welcome to PPCG!

Stax, 11 bytesCP437
ä¢⌠┐xⁿtH↔BU

Try it online!
Unpacked version with 13 bytes:
B|AsF:10i^\=*

Finally tied Husk and beaten by Jelly by just one byte ...
Explanation
B                Push tail (all except 1st row) of the input array, then push the head (1st row)
 |A              All elements in the head are truthy
                 This will be used as an accumulator
   sF            For each element in the tail, execute the rest of the program
     :1          All truthy indices
       0i^\      Expected truthy indices (0 and the current row number)
           =     The truthy indices are as expected
            *    Perform logical "and" with the accumulator
                 Implicit output of the final accumulator

Japt, 16 bytes
Ëe@!X^!(E*Y*nE
e

Test it online!
Man, this takes me back to the good old days when Japt was regularly much longer than other golfing langs...

R, 81 79 bytes
function(x){n=nrow(x);i=c(seq(1,n^2,n+1),1:n,seq(1,n^2,n));all(x[i]>0,x[-i]<1)}

-2 bytes thanks to Mr. Xcoder
Try it online!

79 bytes.

Very nice; I managed to find a 78 byter that's doing something very odd but I also found a 76 byte golf of yours.

69 bytes but I improved mine to 68!

PowerShell, 186 bytes
$a=$($args);if($a[0]-contains0){0;exit};0..($a.Length-1)|%{if($a[$_][0]-eq0-or$a[$_][$_]-eq0){0;exit};$r=$a[$_];$d=$_;if($_-ne0){1..($r.Length-1)|%{if($r[$_]-ne0-and$_-ne$d){0;exit}}}};1

Try it online!

Some golfs -- use param($a) to take input, the -contains can be swapped for an -in and all of the -eq0 can be swapped for !. Finally, you can loop from 1 up to $a.length and get rid of the if($_-ne0) in the loop body.

C, 117 bytes
i,j,r;f(A,n)int*A;{for(i=r=0;i<n;++i)for(j=-1;++j<n;(!i||!j||i==j)&&!A[i*n+j]&&++r)i*j&&i-j&&A[i*n+j]&&++r;return!r;}

Try it online!

Perl 5, 136 + 2 (-ap) = 138 bytes
push@a,[@F]}{push@b,"@{$a[0]}"=~/\b0\b/;map{//;map$a[$'][$_]=!$a[$'][$_],0,$';shift@{$a[$']};push@b,@{$a[$']}}1..$#a;say!("@b"=~y/ 0//c)

Try it online!

Clean, 79 bytes
import StdEnv
?[h:m]=prod h>0&&and[u>0&&n!!x>0&&sum n==n!!x\\[u:n]<-m&x<-[0..]]

Try it online!

K (oK), 27 30 bytes
Solution:
x~a*x|a:a|+(a:1,(#1_x)#0)|=#x:

Try it online!
Explanation:
I must be doing something dumb as the APL solutions are less than half the byte count...
24 bytes spent creating the arrowhead. or together the following three matrices:
/ assume 4x4 matrix
=#x
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

+(a:1,(#1_x)#0)
1 0 0 0
1 0 0 0
1 0 0 0
1 0 0 0

a
1 1 1 1
0 0 0 0
0 0 0 0
0 0 0 0

Full breakdown:
x~a*x|a:a|+(a:1,(#1_x)#0)|=#x: / the solution
                            x: / save input as x
                           #   / count length
                          =    / identity matrix
                         |     / or with
           (            )      / do this together
                      #0       / take from 0
                ( 1_x)         / drop first of x
                 #             / count
              1,               / prepend 1
            a:                 / save as a
          +                    / flip rows/cols
         |                     / or with
        a                      / a
      a:                       / save as a
     |                         / or with
    x                          / x
  a*                           / multiply by arrowhead
x~                             / matches input?

05AB1E, 42 29 28 27 bytes
vyNèP}IнPIøнPPĀiI¦€¦D€às€OQ

Can most definitely without any doubt be golfed quite a bit.. I've only just started with 05AB1E; matrices aren't my strong suit; nor are they 05AB1E's strong suit.. All and all not a great combination..
Try it online or verify all test cases.
Explanation:
vyNè }       # Take the diagonal of the input-matrix
    P        # and calculate its product
             #  i.e. [[1,2,3,4],[5,6,0,0],[7,0,8,0],[9,0,0,10]] → [1,6,8,10] → 480
Iн           # Take the first row
  P          # and take its product as well
             #  i.e. [[1,2,3,4],[5,6,0,0],[7,0,8,0],[9,0,0,10]] → [1,2,3,4] → 24
Iøн          # Take the first column
   P         # and take its product as well
             #  i.e. [[1,2,3,4],[5,6,0,0],[7,0,8,0],[9,0,0,10]] → [1,5,7,9] → 315
      P      # Take the product of all three results,
             #  i.e. [480, 24, 315] → 3628800
       Āi    # If this result is larger than 0
             # (which means the diagonal, first row, and first column contain no zeros)
             #   i.e. 3628800 > 0 → 1
I¦           #  Take the input and remove the first row
             #   i.e. [[1,2,3,4],[5,6,0,0],[7,0,8,0],[9,0,0,10]]
             #          → [[5,6,0,0],[7,0,8,0],[9,0,0,10]]
  €¦         #  And also remove the first item of each row
             #   i.e. [[5,6,0,0],[7,0,8,0],[9,0,0,10]] → [[6,0,0],[0,8,0],[0,0,10]]
    D        #  Duplicate that
     €à      #  Take the max of each
             #   i.e. [[6,0,0],[0,8,0],[0,0,10]] → [6,8,10]
     s€O     #  As well as the sum of each
             #   i.e. [[6,0,0],[0,8,0],[0,0,10]] → [6,8,10]
        Q    #  And check if all maximums and sums are equal
             #  (this means each column and row only contains two numbers (row/column
             #  and diagonal); everything else is a zero)

ćsøćsε¾èˆ)¼}˜OŠ¯)ćs˜ĀP‹ should save you 6 bytes. Try it online! This is most certainly golfable though, but I don't have time to shorten it further now. But nice approach!

@Mr.Xcoder Nice approach as well! Hmm, but it's so different from my approach that I have the feeling it would be better as a separated answer.. If you want you can post it yourself, or I will add it to my answer, but also leave the 29 byte answer (or 28, since Ā instead of 0› would save a byte - was unable to find the one-char command for >0..)

I'll leave that up to you; if you don't include the 23-byter into your answer, I'll post it as a separate one when I get the chance to golf it further. I'm fine either way :)

@Mr.Xcoder Both are also fine by me, so you can post it yourself, since you are the one that came up with it. Let me know when you have, then I will add a link to your shorter 05AB1E answer in mine (and upvote it of course). Normally I wouldn't mind replacing my code with yours, but since the approaches are so different this time you can post it as a separated answer. :) (Have a nice weekend!)

Sure, that works. Have a nice weekend too!

Done, posted my own answer.

05AB1E, 23 bytes
ćsøćsε¾èˆ)¼}˜OŠ¯)ćs˜ĀP‹

Try it online!
This was initially a comment on Kevin's answer, but they told me I should post it separately, and so I did. I should be able to shave off a couple of bytes shortly.

R, 52 bytes
function(m)all(rbind(1,cbind(1,diag(nrow(m)-1)))-!m)

Try it online!
One-liner doing the same as the other R solution by Giuseppe for the same byte count. Giuseppe managed to save one byte before I even posted this!

C# (.NET Core), 73 + 18 = 91 bytes
using System.Linq;
a=>a.SelectMany((b,i)=>b.Select((n,j)=>i<1||j<1||i==j?n>0:n<1)).All(v=>v)

Try it online!
The input is an array of integer-arrays (int[][]) the output is bool.
Ungolfed full program:
using System.Linq;
class Program
{
    static void Main(string[] args)
    {
        System.Func<int[][], bool> f =
        a => a.SelectMany(                          //Iterates through all elements of the outer array, applies the following function and flattens the result
            (b, i) =>                               //b is the inner array, i is it's index
                b.Select(                           //Iterates through all elements of the current array (b) and applies the following function
                    (n, j) =>                       //n is the integer, j is it's index in the inner array (b)
                        i < 1 || j < 1 || i == j ?  //If the current element is in the first row, first column or the diagonal
                        n > 0 :                     //Check if the element is not 0
                        n < 1))                     //else check if the element is 0
            .All(v => v);                           //Check if the value of all elements of the flattened result is true, the result is returned implicitly

        //Truthy test cases
        System.Console.WriteLine(f(new int[][] { new[] { 1, 1, 1 }, new[] { 1, 1, 0 }, new[] { 1, 0, 1 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 1, 2, 3, 4 }, new[] { 1, 1, 0, 0 }, new[] { 1, 0, 1, 0 }, new[] { 1, 0, 0, 1 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 1, 2, 2, 2 }, new[] { 2, 1, 0, 0 }, new[] { 3, 0, 1, 0 }, new[] { 4, 0, 0, 1 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 34, 11, 35, 5 }, new[] { 56, 567, 0, 0 }, new[] { 58, 0, 679, 0 }, new[] { 40, 0, 0, 7 } }));

        //Falsey test cases
        System.Console.WriteLine(f(new int[][] { new[] { 3, 5, 6 }, new[] { 7, 1, 0 }, new[] { 8, 0, 0 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 9, 9, 9, 9 }, new[] { 9, 9, 0, 0 }, new[] { 9, 7, 9, 0 }, new[] { 9, 0, 0, 9 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 1, 0, 3, 4 }, new[] { 1, 1, 0, 0 }, new[] { 1, 0, 1, 0 }, new[] { 1, 0, 0, 1 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 1, 6, 3, 4 }, new[] { 13, 2, 0, 6 }, new[] { 29, 0, 1, 0 }, new[] { 2, 0, 0, 4 } }));
    }
}

Suggest i<1|j<1|i==j instead of i<1||j<1||i==j

PHP, 80 bytes
foreach($_GET[a]as$i=>$r)foreach($r as$k=>$v)($i&&$k&&$i!=$k)==$v&&$b=1;echo!$b;

JavaScript ES6, 97 85 82 bytes
x=>x.map((_,i)=>p(0,i)+p(i,0)+p(i,i),p=(i,j)=>x[i][j]=+!x[i][j])&&!/[1-9]/.test(x)

F =
x=>x.map((_,i)=>p(0,i)+p(i,0)+p(i,i),p=(i,j)=>x[i][j]=+!x[i][j])&&!/[1-9]/.test(x)

console.log(F([[1,2,3,4,5,6],[9,5,0,0,0,0],[4,0,3,0,0,0],[4,0,0,3,0,0],[4,0,0,0,3,0],[4,0,0,0,0,3]]))

console.log(F([[1,2,3,4,5,6],[9,5,0,0,0,0],[4,0,3,0,0,0],[4,0,7,3,0,0],[4,0,0,0,3,0],[4,0,0,0,0,3]]))

console.log(F([[1,2,0,4,5,6],[9,5,0,0,0,0],[4,0,3,0,0,0],[4,0,0,3,0,0],[4,0,0,0,3,0],[4,0,0,0,0,3]]))

@Mr. Xcoder For C the equ of an array is a pointer and a length. For JavaScript I modified so it doesn't take the length

APL NARS, 48 bytes, 24 chars
{(×⍵)≡1⍪1,(⍳∘.=⍳)¯1+↑⍴⍵}

test:
   y←{(×⍵)≡1⍪1,(⍳∘.=⍳)¯1+↑⍴⍵}
   a1 a2 a3
 1 2 2 2   3 5 6   9 9 9 9
 2 1 0 0   7 1 0   9 9 0 0
 3 0 1 0   8 0 0   9 7 9 0
 4 0 0 1           9 0 0 9
   y¨a1 a2 a3
1 0 0

Java 8, 95 bytes
A lambda from int[][] to int (0 is false, 1 is true).
m->{int i=0,d=m.length,r,c,f=1;while(i<d*d)f=m[r=i/d][c=i++%d]<1==(r*c*(r-c)!=0)?f:0;return f;}

Try It Online
Ungolfed
m -> {
    int
        i = 0,
        d = m.length,
        r, c,
        f = 1
    ;
    while (i < d * d)
        f =
            m[r = i/d][c = i++%d] < 1
                == (r * c * (r-c) != 0) ?
                    f
                    : 0
        ;
    return f;
}

Ruby, 65 bytes
->a{(r=0...a.size).all?{|i|r.all?{|j|(a[i][j]>0)^(i!=j&&i*j>0)}}}

Try it online!

Attache, 33 bytes
{DrawMatrix["\\<:^>",#_]==Clip!_}

Try it online!
DrawMatrix takes a string and a matrix size and "draws" it. In this case, we generate a base arrowhead matrix, like so:
\<:^>
\      draw a line from the top left to the bottom right
 <:    move to the left
   ^   draw a line up to the top
    >  draw a line right to the left

Then, we check for equality with the input matrix, replacing nonzeroes with 1.


text:
Now we're thinking in n dimensions!
The question: Given an a number n ≥ 2, how many distinct pairs of points on an n-dimensional n x n x n x n x n x n ... x n lattice, where the coordinates range from 0 to n - 1, are a distance at least n apart? The pairs {(2,1,3,1), (3,2,1,3)} and {(3,2,1,3), (2,1,3,1)} are not considered distinct from each other, as they consist of the same two points in reverse order. Note that the total number of pairs grows very rapidly. The number of total pairs goes 6, 351, 32 640, 4 881 250, 1 088 367 840, etc.
Test cases:
2 -> 0 (all pairs are at most a distance of sqrt(2) < 2 apart)
3 -> 28 (They must either be (2,2,1) or a permutation apart, or (2,2,2) apart. Each corner
has three non-corner (2,2,1) points corresponding to it. And each corner is associated
with a corner pair that is a (2,2,2). Thus. 3.5 * 8 = 28.
4 -> 4,888
5 -> 1,501,948
6 -> 486,039,360 (I would like someone to verify this if possible)

Your code should work for n <= 5, at least in theory. Don't hardcode it, that's a standard loophole.

https://tio.run/##bZLbboMwDIav4Sm8SpWSAONQbRfVuhepqgmRsEaioQpU256e2UkZh/UKYv/@7Pzx9ac/t2Y3DFLVUDPD92EgddeXplJwgGN2EiYMGn3RfTed69aCBm3AluZT@aq76KhPqNOmZ4wZYZKcp8wkmnMhsucXHgZWEShDSFn1rdVlg8f8H7OITZQ77qQTCA6Dr7NuFPwN@XQA35m02lT2QxupvhGKzTG0lB8nBc45ls6jhJlzEjdd8BAQ@dxq9EkR5bH3ZlZO9jyC0fQ1dLcLk0ICISUhRymHN0A/Hcw7gpw/ayhataZTlfcWTzdLCmfB4/dy/RZzHYCqfG7E3a84dU1TlLmcC6umU2OFbzlDLkgj6M4R9EBr7Wqid8j2i@ZYVFCAliga70871d@sAVw4YbhwH1q8tIAEUIo/w8qCXZy/kgtXS6u62WaFhD1sJWy2TMc1w4Xlwy8

^ a program that can produce results for n=15 easily

https://tinyurl.com/ya2kmb24 <-- ported to C which can calculate up to n=20 but suffers heavily from overflow

How are you measuring distance? Euclidean metric? Or given that it's a lattice are you using L_1?

@PeterTaylor from the test cases, it's clear that we're using Euclidean distance all pairs are at most a distance of sqrt(2) apart but that should be specified more clearly.

MATL, 12 bytes
tt:Z^tZPR>~z

Try it online!
Explanation
tt   % Implicit input n. Duplicate twice
     % STACK: n, n, n
:    % Range [1 2 ... n]
     % STACK: n, n, [1 2 ... n]
Z^   % Cartesian power. Gives an n^n × n matrix C where each row is a Cartesian tuple
     % STACK: n, C
t    % Duplicate
     % STACK: n, C, C
ZP   % Euclidean distance. Gives an n^n × n^n matrix D of pairwise distances
     % STACK: n, D
R    % Upper triangular part: sets elements below the main diagonal to 0. Call that U
     % STACK: n, U
>~   % Less than or equal? Element-wise. Gives a true-false matrix B
     % STACK: n, B
z    % Number of nonzeros. Implicitly display
     % STACK: number of entries in B that equal true

J, 40 bytes
2%~[:+/^:_]<:[:+/&.:*:"1[:-"1/~#~#:i.@^~

Try it online!
Will time out on TIO for 5 if you use extended precision (5x instead of 5). I'm not going to bother trying with 6 on my computer since that will no doubt crash the interpreter.
Looking for advice on golfing, specifically the part past the generation of the coordinates. I feel like there ought to be a way to remove some of the caps.
]<:[:+/&.:*:"1 may be equivalently replaced by *:<:[:+/"1[:*:.
Explanation
This explanation is done on the REPL (three spaces indicate a command, no spaces indicate an output). I will be building up to the answer.
Generating the coordinates
#~ #: i.@^~ gives all the coordinates we care about on the lattice.
^~ is a number raised to itself, and i. gives the range [0,n)
 where n is its input. @ composes those functions.
   i.@^~ 2
0 1 2 3

#~ copies a number by itself, e.g.
   #~ 3
3 3 3

#: converts its right argument to the base specified by the array given as its left argument. The number of digits in the array corresponds to the number of digits in that base output (and you can have a mixed base) For example,
   3 3 3 #: 0
0 0 0
   5 5 #: 120
4 0
NB. If you want 120 base 5 use #.inv
   #.inv 120
4 4 0

So, all together, this says enumerate through all of the values base n (where n is the input) up to n^n, effectively giving us our coordinates.
   (#~ #: i.@^~) 2
0 0
0 1
1 0
1 1

Getting the distances between each pair
First we take the difference of each coordinate with all of the others using the dyad /-table and ~-reflexive. Note that this doesn't account for the fact that order doesn't matter for the pairs: this generates duplicate distances.
  NB. 2 {. takes the first two elements (I'm omitting the rest).
  2 {. -"1/~ (#~ #: i.@^~) 2
 0  0
 0 _1
_1  0
_1 _1

 0  1
 0  0
_1  1
_1  0

Then we use this verb +/&.:*: on each coordinate (at "1, aka rank one). This verb is sum (+/) under (&.:) square (*:). Under applies the right verb (square) then collects its results and gives it as the argument to the left verb (sum). It then applies the inverse of the right verb (which would be square root).
   +/&.:*: 3 4
5
   +/&.:*:"1 ([: -"1/~ #~ #: i.@^~) 2
      0       1       1 1.41421
      1       0 1.41421       1
      1 1.41421       0       1
1.41421       1       1       0

Unsurprisingly, many distances are the same.
Counting the distances greater than or equal to the input
The last part is seeing if the distance is greater than or equal to the input using ]<:. Then all of the results are summed using +/^:_ (sum until converge), counting the number of truthy values. Then this value is divided by 2 (2%~, here ~ means swap the order of the arguments supplied to %). The reason why we can divide by 2 is because for each truthy pairing, there will be another one for the flipped order except for pairings which are a coordinate with itself. That's ok, though, since those will result in a distance of 0.

35 bytes with +/@,@(-:@<:+/&.:*:@:-"1/~)#~#:i.@^~

Jelly, 14 13 bytes
1 byte thanks to Dennis.
ṗ⁸Œc_/€ÆḊ€<ċ0

Try it online!
Quick maffs version
ŒgL€!P:@L!$×P
²S<
ḶœċçÐḟ²ð>0S’2*×⁸ạ⁹$Ñ¤ð€S

Try it online!

What interpreter do you use to run this? I want to try it but TIO is too slow for n=5 (timed out after 1 minute) http://prntscr.com/hqbcph

@bushdid911 if you try to break the limit, broken the limit will be

You can replace æ.`½ with ÆḊ€.

@bushdid911 It can run n=5, just not in one minute. (it may take more than the age of the universe, be careful) This is not fastest code, so why bother make your code run fast?

If it can run n=5 in 10^500 years that is fine, as long as it works theoretically. That's what i was getting at there.

@bushdid911 I made a fast(er) version.

Can you explain that 2nd one? @LeakyNun

@bushdid911 it works mainly like how you calculated. It generates tuples representing permissible distances and counted the number of pairs of points with required distance.

Python 2, 137 133 bytes
lambda n:sum(n*n<=sum((o[i]-p[i])**2for i in range(n))for o,p in q(q(range(n),repeat=n),repeat=2))/2
from itertools import*
q=product

Mr Xcoder & ovs: -4 bytes.
Try it online!

135 bytes. (No need to include f=)

133 bytes

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Find the smallest triangle encompassing the specified polygon
Input: An integer N which represents the polygon's vertices and a list of their x and y coordinates.
Expected output: The smallest difference possible between the area of the(not necessarily convex) polygon and the triangle containing it. The triangle also has to share at least 2 vertices with the polygon. If there is no such triangle print -1.
Example:
4
0,0
2,0
1,1
0,2

Output: 0, because the polygon matches up perfectly with the triangle.
This is code-golf so answers will be scored in bytes with less bytes being better.

Welcome to PPCG! As it stands, your question is a little unclear. Could you provide some example inputs and outputs?

Of course, sorry!

Also, most challenges on this site tend to be asking for answers to be shortest in length. If this is the case, please add the [tag:code-golf] tag to your post.

If there is no such triangle print -1 the standard on this site is to ignore invalid inputs, letting them lead to undefined beviour or erroring out.

apart from that, although it lacks a bit of sources to help people who are not familiar with these subjects (not mandatory), this is a good challenge.

@Uriel Ignoring invalid input isn't a standard iirc, it's just sometimes a recommendation. It is by no means mandatory.

How does any triangle match up perfectly with ((0,0),(2,0),(2,1),(0,2))? EDIT: should the (2,1) be (1,1)? (I believe the answer for using the (2,1) would be 1)

Yes, it is 1,1. Sorry about the mistake.

It isn’t quite clear which way “The triangle also…” is supposed to modify the previous sentence. Do you mean “find the smallest triangle among all triangles that both contain the polygon and share at least 2 vertices with it”? Or do you mean “find the smallest triangle among all triangles that contain the polygon; then, if that triangle doesn’t share 2 vertices with it, print −1”? Please edit the question to clarify this.

The first of your questions. “find the smallest triangle among all triangles that both contain the polygon and share at least 2 vertices with it”

Another case of “Should’ve been sandboxed”, otherwise nice question

You mention that the polygon is not necessarily convex. Is it possible that it won't be concave either (i.e. that it will be complex)?

@Uriel There must be such a triangle. Also  are the terms complex enough for more explanation? "A triangle is a polygon with 3 sides"? Doesn't seem good to me.

Python 3.9.12: 588 585 583 580 578 572 bytes
3 bytes saved thanks to Jiří, and 2 bytes saved thanks to clarification from att!
from numpy import*
from itertools import*
def J(V):
 c,a,X,I=combinations,array,cross,vstack;V=[*map(a,V)];s=lambda A,B,P:sign(X(B-A,P-A));Q=lambda v,w,G:all((_:=[x for p in G if any(p-v)*any(p-w)*(x:=s(v,w,p))])==_[0]);F=lambda Z:abs(sum([linalg.det(I((Z[i],Z[i+1])))for i in range(len(Z)-1)]))/2;W=[a([_[0]/_[2],_[1]/_[2]])for k,l in c([a([v,w])for v,w in c(V,2)if Q(v,w,V)],2)if(_:=X(X((h:=hstack((I((k,l)),ones((4,1)))))[0],h[1]),X(h[2],h[3])))[2]!=0];return min([F(e)-F(V)for v,w in c(V,2)for k in W if s(*(e:=[v,w,k]))and Q(w,v,D:=V+e)*Q(k,w,D)*Q(v,k,D)],default=-1)

ATO link
The input for the number of vertices is ignored since it is not used or needed.
The function J takes in the input vertices, V, as a list of tuples/lists. An example function call would be J([(0,0),(1,3),(1,1),(2,0)]).
The code assumes that a polygon is defined as most people would define a polygon (made of vertices connected by non-intersecting edges)
Code explained by line/function
from numpy import*
from itertools import*
def J(V):
 c,a,X,I=combinations,array,cross,vstack;

Normal byte-saving code. Nothing fancy.
V=[*map(a,V)];

Converting the list of tuples into a list of numpy arrays. This can't be left as a map object because of some stuff that is done later.
s=lambda A,B,P:sign(X(B-A,P-A));

s takes in three points A,B,P and returns which side of the line connecting AB is point P using the cross product. The two vectors have two elements so numpy treats them as vectors of the form [x,y,0] and returns only the z component. If P is on the "right" of the line AB, s = -1. On the left, s = +1. If P is on the line AB then s = 0.
Q=lambda v,w,G:all((_:=[x for p in G if any(p-v)*any(p-w)*(x:=s(v,w,p))])==_[0]);

Q takes in two points, v and w, and a set of vertices G. Essentially, this is checking if the line vw places all points in G into the same half of the plane (or onto the line). If that is the case, then it returns True. Otherwise, False. any(p-v) is used instead of the more traditional p==v because numpy arrays can't be directly compared in that way due to "ambiguity".
F=lambda Z:abs(sum([linalg.det(I((Z[i],Z[i+1])))for i in range(len(Z)-1)]))/2;

F takes in Z, a list of vertices of a polygon, and returns the area of that polygon using the shoelace formula. This doesn't work with polygons whose edges intersect, but those polygons have ill-defined areas anyway.
W=list([a([_[0]/_[2],_[1]/_[2]])for k,l in c([a([v,w])for v,w in c(V,2)if Q(v,w,V)],2)if(_:=X(X((h:=hstack((I((k,l)),ones((4,1)))))[0],h[1]),X(h[2],h[3])))[2]!=0]));

Breaking this down:
[a([v,w])for v,w in c(V,2)if Q(v,w,V)] returns a list of 2x2 numpy array the represents the line formed by the points vw, where every combination of two points in the input polygon V gets a chance at being vw, if the line vw places all points in V onto one side of the plane (or on the line). The reason for this is to get a set of lines that forms the boundary of the polygon. Think of it as taking all the vertices that would make the input polygon convex, connecting them with edges, then extending those edges into lines.
The rest of this line is devoted to determining where those lines intersect (if they were extended infinitely far). This is done using homogenous coordinates. Another example can be found in this stackoverflow thread, whose code this is based on.
The reason for this is to determine exactly where could the vertices of the all of the triangles that could envelop the input polygon lie.
min([F(e)-F(V)for v,w in c(V,2)for k in W if s(*(e:=[v,w,k]))and Q(w,v,D:=V+e)*Q(k,w,D)*Q(v,k,D)],default=-1)

This one is very simple. For every combination of points v,w in V and then every point in W (the line intersections), first check to see if all three points are collinear using the function s. If they're not, then we check to see if all points in V are inside of the triangle formed by vwk. This is done by checking if all of the points in V, also including the three points v,w,k, are all on the same side of the plane when intersected by a line made of two of the points. Since it's a triangle, if all the "third points" are on the same side of the plane as the two points forming a line (for all three combinations of v,w,k), then all points must be inside the triangle or on the edge of it.
Lastly, we take get the area of each triangle that satisfies our conditions and subtract off the area of the input polygon. Then, the minimum area is returned. If there is no minimum area to return (because no triangle exists that satisfies all conditions), then -1 is returned instead.

This is my first code golf answer so please let me know if I missed anything major with the question or if there is somewhere bytes can be saved!

Welcome to Code Golf -- this is a really well-explained, in-depth answer!

If you want to, you can add link to ATO or TIO, so people can easily try out your code.

Also you can use V=[*map(a,V)]; instead of V=list(map(a,V)); to save few bytes.

@Jiří I have added your suggestions. Thank you! :D

Input may be entirely ignored

Found a bug: if the vertices of the input polygon are given in a clockwise order rather than anticlockwise, the area calculation is not correct. Is this something that needs to be fixed, or is stipulating that the input has to follow those criteria okay?

447 bytes

413

365. You usually shouldn't assume restrictions not explicitly stated in the problem.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Organize Your Christmas Party!
Christmas is coming up, and this year you have been charged with organizing your family's christmas get-together. You have a list of foods you want be there, but before you assign foods to people, you need to know who's coming. So...
Challenge
Given an input of relative's names separated by commas or whatever (note that the names may have spaces in them, e.g. "Aunt Gertrude") and a list of meals including turkey, divide the meals among them equally, but saving the turkey and any extra for yourself, because you don't want to be unfair. In other words, if 6 people are coming and there are 10 meals, you have to do the turkey and 3 others, because 6 goes into 9 once, leaving 4 for you.
Input will never have more people than meals.
Full list of possible dishes  (Taken from Wikipedia)

Apple Cider
Boiled Custard
Candy canes
Champagne
Chocolate fudge
Christmas cookies
Cranberry sauce
Eggnog
Fish
Fruitcake
Gingerbread Men
Christmas ham
Hot buttered rum
Hot chocolate
Mashed potato
Mixed nuts
Oyster stew
Persimmon pudding
Apple pie
Pecan pie
Pumpkin pie
Sparkling cider
Stuffing
Sweet potato pie
Sweet potato casserole with marshmallow
Russian tea cakes
Tom and Jerry
Turkey

Here is a formatted version if you prefer:
["Apple Cider","Boiled Custard","Candy canes","Champagne","Chocolate fudge","Christmas cookies","Cranberry Sauce","Eggnog","Fish","Fruitcake","Gingerbread Men","Christmas Ham","Hot buttered rum","Hot chocolate","Mashed potato","Mixed nuts","Oyster stew","Persimmon pudding","Apple pie","Pecan pie","Pumpkin pie","Sparkling cider","Stuffing","Sweet potato pie","Sweet potato casserole with marshmallow","Russian tea cakes","Tom and Jerry","Turkey"]

Name format
Relative's names will take any of the following formats

Aunt x
Uncle x
Creepy Uncle x
Grandpa x
Grandma x
Cousin x
Mother-in-law x
Father-in-law x
Papa x
Nana x
x
x can be any 20 char or less combination of upper/lower case letters

I/O
Input can be taken in any reasonable, convenient format, but I will assume list if not otherwise specified: [relative a,b,c],[food x,y,z]
Output can also be in any reasonable convenient format, I personally prefer a list of lists You do not need to output the turkey or extra meals
Examples

["Aunt Gertrude", "Cousin Sally", "Grandpa Joe", "Creepy Uncle Rick"],["Sparkling Cider", "Pumpkin Pie", "Pecan Pie", "Oyster Stew", "Chocolate Fudge", "Turkey"] -> [["Aunt Gertrude","Sparkling Cider"],["Cousin Sally", "Pumpkin Pie"],["Grandpa Joe","Pecan Pie"],["Creepy Uncle Rick","Oyster Stew"]]

["Aunt getoFFmyLAWn","Grandpa Lipbalm","Cousin onlyplaysroblox","Papa losthisjob"],["Pumpkin pie","Sparkling cider","Stuffing","Sweet potato pie","Sweet potato casserole with marshmallow","Russian tea cakes","Tom and Jerry"] -> [['Aunt getoFFmyLAWn', 'Pumpkin pie'], ['Grandpa Lipbalm', 'Sparkling cider'], ['Cousin onlyplaysroblox', 'Stuffing'], ['Papa losthisjob', 'Sweet potato pie']]

As christmas is almost here, you don't have time to be planning more than needed, so use those code-golf skills and program up some lists!
Notes

No standard loopholes
If you have only a function, please provide code to call it as well
Please provide an explanation
Smallest byte count ~ 2-3 days after Christmas wins!

Most votes by ~ 2-3 days after Christmas wins! but you have tagged your challenge [tag:code-golf] (I suggest removing the last note, and don’t make this a bad pop-con!)

@Mr.Xcoder good catch!

@JonathanAllan Fixed

Can the x in the names contain spaces (e.g. "Cousin George jr.")?

@Titus no you are not required to add that capability

Jelly, 17 bytes
I went off-piste with the meals in my example without realising! It shouldn't matter I think, and looks tastier to my British eyes.
ḟ“Øẇ½»W¤s⁹L‘¤ṖZṖż

A dyadic link taking a list of foods (lists of characters) on the left and people (also lists of characters) on the right which returns a list containing a list per person containing a list of characters (their name) and a list of foods (each a list of characters).
e.g. (using "..." to represent a list of characters):
left = ["Champagne", "Turkey", "Stuffing", "Port", "Roast Potatoes", "Brussel Sprouts", "Parsnips", "Pigs In Blankets", "Gravy", "Steamed Vegetables", "Cheese Plate", "Christmas Pudding"]
right = ["Aunt Gertrude", "Cousin Sally", "Grandpa Joe"]

output = [[["Champagne", "Brussel Sprouts"],"Aunt Gertrude"],[["Stuffing", "Parsnips"],"Cousin Sally"],[["Port", "Pigs In Blankets"],"Grandpa Joe"]]

(leaving us with Turkey, Roast Potatoes, Gravy, Steamed Vegetables, and Christmas Pudding.)

Try it online! (The footer calls the dyadic link and then pretty prints the result)
How?
ḟ“Øẇ½»W¤s⁹L‘¤ṖZṖż - Link: foods, people
            ¤     - nilad followed by link(s) as a nilad:
         ⁹        -   chain's right argument, people
          L       -   length
           ‘      -   increment (add yourself to the cook count)
       ¤          - nilad followed by link(s) as a nilad:
 “Øẇ½»            -   compressed string = list of characters, ['T','u','r','k','e','y']
      W           -   wrap in a list                          [['T','u','r','k','e','y']]
ḟ                 - filter discard (from foods) if exists in that list (we cook any Turkey)
        s         - split (the resulting list of foods) into chunks (of number of cooks)
             Ṗ    - pop off the excess
              Z   - transpose to a list of fair shares
               Ṗ  - pop off our share
                ż - zip with people names (to provide the allocations)

That looks to be a brilliant Christmas lunch! Who doesn't like pigs in blankets!

Operation Flashpoint scripting language, 155 bytes
f={t=_this;a=t select 0;b=(t select 1)-["Turkey"];i=0;d=count a;e=count b;c=e/d;c=c-c%1;while{i<c*d}do{a set[i%d,(a select i%d)+","+(b select i)];i=i+1};a}

Call with:
array = [["Aunt Gertrude", "Cousin Sally", "Grandpa Joe", "Creepy Uncle Rick"],["Sparkling Cider", "Pumpkin Pie", "Pecan Pie", "Oyster Stew", "Chocolate Fudge", "Turkey"]];
hint format["%1", array call f]

Output:

wth this is awesome

PHP, 112 bytes
function($p,$f){return array_combine($p+[($n=count($p))=>0],array_chunk(array_diff($f,[Turkey]),count($f)/$n));}

anonymous function, takes an array of people and an array of meals,
returns an associative array name=>array of meals plus one element 0=>extra meals (without the Turkey).
Try it online.


text:
Form a list using prime numbers
You have been given N piles of coins. You have decided to divide each of those B1, B2, ..., BN piles among separate groups of people. The amount of people receiving coins has to be a prime number and the amount of money given to each person must be different in each pile.
Input: N, B1, B2, ..., BN (The amount of coins in each individual pile).
Output: NP1, NP2, ..., NPN with NP being the number of people(prime number) receiving the coins. If this is impossible then yield some unachievable result (like 0, -1, None, [], or "impossible") or raise an error.
Example:
3
7 8 9

Output: 7 2 3
Because 7 is the only prime number that can divide 7 evenly, the same for 8 and 2 and 9 and 3. Also, notice that (7 / 7 = 1) ≠ (8 / 2 = 4) ≠ (9 / 3 = 3).

N is a redundant input, may we forego taking it?

May we yield some other non-achievable result (e.g. 0, an empty list, a string like "impossible", or raise an error) for impossible cases? (I'd actually recommend only valid input, or allowing undefined behaviour in such cases, but it's up to you.)

You may forego the input of N. And yes to the second question.

So, the lowest prime divisor of each number?

@totallyhuman not quite - if the input were say [7,8,8] it would be impossible (since using 2 for both 8 results in two 4s.) Furthermore, if the input were say [7,30,30] then [7,2,2] would be invalid but [7,2,3] and [7,3,2] amongst others would work.

...And the lowest non-1 divisor of a number is always prime.

@JonathanAllan So it's lowest non-1 divisor of each and if the list contains only unique elements.

@totallyhuman no - the output for [7,8,16] may ONLY be [7,2,2] - this list does not only contain unique elements (it's the division results that must be unique).

Why doesn't {5, 11, 2} work for your example of 3 piles with 7, 8, and 9 coins in each?  That gives 24 coins to divide up. Correct?

05AB1E, 13 bytes
Ò.»â€˜ʒ÷DÙQ}θ

Try it online!
A port of my Pyth answer.

Ò gets the prime factÒrs of each.
.» folds a dyadic command, â (cârtesiân product) between each two elements in the list from right to left with opposite right/left operands.
€˜ flattens €ach.
ʒ...} filtʒrs those which satisfy the following condition:

÷ pairwise integer division with the input.
D Duplicate (pushes two copies of the item to the stack).
Ù removes duplicate elements, keeping a ÙniqÙe occurrence of each element.
Q checks for eQuality.

θ gets the last element.

Jelly,  15  14 bytes
³:ŒQẠ
ÆfŒpÇÐfṪ

A full-program which accepts one argument, a list of numbers, and prints a representation of another list of numbers, or 0 if the task is impossible.
Try it online!
How?
³:ŒQẠ - Link 1, unique after division?: list of primes, Ps   e.g. [7,2,2]  or  [7,3,3]
³     - program's first input                                e.g. [7,8,8]  or  [7,9,30]
 :    - integer division by Ps                                    [1,4,4]      [1,3,10]
  ŒQ  - distinct sieve                                            [1,1,0]      [1,1,1]
    Ạ - all truthy?                                               0            1

ÆfŒpÇÐfṪ - Main link: list of coin stack sizes, Bs   e.g. [7,8,12]
Æf       - prime factorisation (vectorises)               [[7],[2,2,2],[2,2,3]]
  Œp     - Cartesian product                              [[7,2,2],[7,2,2],[7,2,3],[7,2,2],[7,2,2],[7,2,3],[7,2,2],[7,2,2],[7,2,3]]
     Ðf  - filter keep if:
    Ç    -   call last link (1) as a monad                 1       1       0       1       1       0       1       1       0
         -                                                [[7,2,2],[7,2,2],[7,2,2],[7,2,2],[7,2,2],[7,2,2]]
       Ṫ - tail (note: tailing an empty list yields 0)    [7,2,2]
         - implicit print

+1 Haha, I think µ⁼Q would work as an alternative to the fancy distinct sieve, but good job!

Pyth, 15 bytes
ef{I/VQT.nM*FPM

Try it here!
How?

ef{I/VQT.nM*FPM | Full program, which foregoes the size.
                |
             PM | Prime factorisation of each integer.
           *F   | Fold Cartesian Product over the list of primes.
        .nM     | Flatten each.
 f              | Filter.
  {I/VQT        | Filter condition (uses a variable T).
    /V          | Vectorised integer division...
      QT        | Over the input and the current item.
  {I            | Is invariant over deduplication (removing duplicates)?
e               | Take the last element.
                | Output the result implicitly.


text:
Draw an ASCII key signature
Given an input of a note, output an ASCII drawing of the corresponding major
key on the treble clef.
Here are all the major keys (that don't include double-sharps or double-flats)
and their corresponding key signatures:

Circle of fifths deluxe 4 by Wikipedia user Just plain Bill, copyright CC BY-SA 3.0
If the input is a key with sharps, draw the following ASCII art with the
appropriate number of sharps:
   #
-#-------
      #
----#----
  #
-------#-
     #
---------

---------

And if the input is a key with flats:
---------
  b
----b----
      b
-b-------
   b
-----b---
       b
---------

Here is a concise summary of the possible inputs as well as how many sharps or
flats they use:
   0   1   2   3   4   5   6   7
#  C   G   D   A   E   B   F#  C#
b  C   F   Bb  Eb  Ab  Db  Gb  Cb

All five lines of dashes must always be drawn, but there may be any number of
dashes per line such that the sharps or flats have at least one column of
padding on each side, as long as each line of dashes has the same length. For
example, these are all also acceptable outputs for the input Ab:
---------   ------   ---------   ----------------
  b           b           b          b
----b----   ----b-   -------b-   ------b---------

-b-------   -b----   ----b----   ---b------------
   b           b           b          b
---------   ------   ---------   ----------------

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

In the case of C major, which has no sharps nor flats, any positive number of dashes per
line (even one) is acceptable.
Any amount of leading or trailing whitespace is fine, as are trailing spaces on
each line. Extra leading spaces are okay as long as there are the same number
on each line.
You may take input in lowercase or require that inputs without a sharp or flat contain a trailing space, if you so desire.
Since this is code-golf, the shortest solution in bytes will win.

Related

@Neil Ah, sorry for stealing your challenge >_< I searched the main site before posting but didn't think to check the sandbox.

Python 2, 206 197 178 175 168 161 bytes
Thanks to Mr. Xcoder for -12 bytes!
This is a function which returns the result as a 2D list of characters. If the input does not contain a sharp/flat, it should be padded with a space.
def f(k,r=range(10)):n="CGDAEB".find(k[0])+7*' #'.find(k[1]);return[[(' -'[i%2],'b#'[n>0])[0<j<=abs(n)and`i`==(n*"1403625"+"5263748")[j-1]]for j in r]for i in r]

Try it online!

I think "FCGDAEB".find(k[0])-1 maps F to -1 and the others to their index - 1, so I think n="CGDAEB".find(k[0])+7*('#'in k)-7*('b'in k) would work instead. (175 bytes?)

@Mr.Xcoder That's smart... thank you.

Charcoal, 60 bytes
≔⁻⁺⊖﹪⊗℅§θ¬χ⁷×⁷№θ#×⁷№θbθ←ＵＯ⁹¦⁹-¶Ｆθ«Ｊι⊖﹪⊕×³ι⁷#»Ｆ±θ«Ｊι⊕﹪⁺³×⁴ι⁷b

Try it online! Link is to verbose version of code. Explanation:
≔⁻⁺⊖﹪⊗℅§θ¬χ⁷×⁷№θ#×⁷№θbθ

Calculate the number of sharps in the key signature.
←ＵＯ⁹¦⁹-¶

Print the stave, but one square left of the origin so that the first sharp/flat is in column zero.
Ｆθ«

Loop over any sharps.
Ｊι⊖﹪⊕×³ι⁷#»

Calculate the row of the sharp and print it.
Ｆ±θ«

Loop over any flats.
Ｊι⊕﹪⁺³×⁴ι⁷b

Calculate the row of the flat and print it.

Befunge, 139 bytes
~9%:4%7*+4/7%~6%1-2/7*+vv\`0:\!-g02+*2g00+1%7+g00*+3g00::<<0+55p02:_@
- b#09p01*-1*2p00:`0:-8<>10g`!**:00g2+*\!20g2%*+1g,1+:8`!#^_>$,:1-\^1

Try it online!
Note that the input is expected to be terminated with a linefeed, as would typically occur when running the program interactively.
Explanation
We start by reading two characters from stdin - the main note, n, and an accidental, a (which can be a linefeed if there is no accidental). Using those values, we calculate the key signature number, signum, as follows:
signum = (n%9 + n%9%4*7)/4%7 + (a%6 - 1)/2*7 - 8

This returns a value in the range -7 to 7, where the sign tells us whether we need sharps or flats (positive or negative), and the absolute value gives us the number of sharps or flats required. So for later use, we extract the sign, s, and the the accidental count, cnt, with:
s   = (signum > 0)
cnt = abs(signum)

Then we have two nested loops, iterating a row number, r, from 9 down to 0, and a column number, c, from 0 up to 8. For a particular row and column, we calculate whether an accidental should be visible at that point with:
accidental = (r == (c*(s+3) + s)%7 + 1 + s*2) and (c > 0) and (c <= cnt)

If it's not an accidental, we need to output a line or space depending on whether the row, r, is odd or even. And if it is an accidental, we need to output a sharp or flat depending on the sign, s. So we evaluate the following formula:
index = (!accidental * (r%2)) + (accidental * (s+2))

Which gives us an index in the range 0 to 3, representing either a line, a space, a flat or a sharp. We simply use that index to lookup the required output character from a table, which you can see embedded at the start of the second line of code.


text:
Loan "generous" amounts of money
Introduction
You have a friend that keeps asking you for loans and you are getting tired of it. Today, he came for a loan again.  Instead of turning down his offer, you get a great idea: troll your friend by giving him as many coins/bills as possible.
Challenge
You will take as input: the amount of money your friend wants a loan for and the amount of coins/bills you have. For this challenge, the possible denominations are $20.00, $10.00, $5.00, $2.00, $1.00, $0.25, $0.10, $0.05, and $0.01. An example of input is 5.67, [5, 3, 4, 5, 5, 9, 8, 1, 2] if you friend wants $5.67 and you have 5 $20 bills, 3 $10 bills, etc. Your output will be the amount of coins/bills that gives your friend as much metal/paper/plastic as possible.
If it is not possible to give your friend the exact amount of money he wants, give him the closest amount of money you can pay that is greater than what he wants. For example, if your friend wants $0.07 but you only have [0, 0, 0, 0, 0, 2, 4, 2, 0], give him 2 $0.05 coins (not 1 $0.10 because that wouldn't be giving him as many coins as possible!).
If your friend wants more money than you have, give him all your money (and pray you won't need to buy anything).
Test cases
Input:  6.54, [9, 8, 7, 6, 5, 4, 3, 2, 4]
Output: [0, 0, 0, 1, 4, 1, 2, 1, 4]

Input:  2, [0, 1, 0, 0, 0, 0, 0, 0, 0]
Output: [0, 1, 0, 0, 0, 0, 0, 0, 0]

Input:  9999, [0, 0, 0, 0, 0, 0, 0, 0, 1]
Output: [0, 0, 0, 0, 0, 0, 0, 0, 1]

Input:  0, [99, 99, 99, 99, 99, 99, 99, 99, 99]
Output: [0, 0, 0, 0, 0, 0, 0, 0, 0]

This is code-golf so shortest code wins.

You have 2.00 and 20.00 but no 0.2 or 0.02 :(

@Mr.Xcoder many challenges uses very arbitrarily chosen currency systems. We might want to make a meta to decide whether currency related challenges should determine their own system, have a single universal system agreed upon, allow the usage of several systems or even make all this challenges to also support the system as input, although that might result in input-validation symptoms for some langauges

@Mr.Xcoder Perhaps you're thinking of two-dollar bills? I was thinking toonies.

Do our answers need to run for all inputs, just for the ones posted, or can they work for small inputs, but fail for the 4th one?

@jrtapsell Input 4 shouldn't cause problems though? 99 is generally a small enough number.

Who are the downvoters?

Clean, 167 bytes
import StdEnv
@n l#m=[p\\p<-[[if(y==u)(x-1)x\\x<-l&y<-[0..]]\\u<-[0..]&v<-l|v>0]|sum[a*b\\a<-[2000,1000,500,200,100,25,10,5,1]&b<-p]>=toInt(n*100.0)]
|m>[]= @n(hd m)=l

Defines the function @, taking Real and [Int].
Try it online!

JavaScript, 213 Bytes
x=>y=>(F=(x,y,z,u=9)=>u--?[...Array(y[0]+1)].map((_,i)=>F(x-i*[1,5,10,25,100,200,500,1e3,2e3][u],y.slice(1),[...z,i],u))&&G:x>0||G.push([z,x-1/eval(z.join`+1+`)]),F(x*100,y,G=[]).sort((a,b)=>b[1]-a[1])[0]||[y])[0]

It's pretty slow and cost memory, so only try small cases

Kotlin, 298 bytes
{t,c->with(c.fold(listOf(listOf<Int>())){o,x->o.flatMap{a->(0..x).map{a+it}}}.groupBy{it.zip(C).map{(a,b)->a*b}.sum()}.mapValues{(_,b)->b.maxBy{it.sum()}!!}.toSortedMap().asSequence()){firstOrNull{it.key==t}?:firstOrNull{it.key>t}?:last()}.value}
val C=listOf(20.0,10.0,5.0,2.0,1.0,0.25,.1,.05,.01)

Beautified
        { t, c ->
            with(c.fold(listOf(listOf<Int>())) { o, x ->
                o.flatMap { a -> (0..x).map { a + it } } /* Get all of the options. */
            }.groupBy { it.zip(C).map { (a, b) -> a * b }.sum() }
                .mapValues { (_,b)->b.maxBy { it.sum() }!! }
                .toSortedMap().asSequence()) {
                firstOrNull { it.key == t } ?:
                        firstOrNull { it.key > t } ?:
                        last()
            }.value
        }
val C = listOf(20.0, 10.0, 5.0, 2.0, 1.0, 0.25, .1, .05, .01)

Test
val calc: (target: Double, coins: List<Int>) -> List<Int> =
{t,c->with(c.fold(listOf(listOf<Int>())){o,x->o.flatMap{a->(0..x).map{a+it}}}.groupBy{it.zip(C).map{(a,b)->a*b}.sum()}.mapValues{(_,b)->b.maxBy{it.sum()}!!}.toSortedMap().asSequence()){firstOrNull{it.key==t}?:firstOrNull{it.key>t}?:last()}.value}
val C=listOf(20.0,10.0,5.0,2.0,1.0,0.25,.1,.05,.01)

data class Test(val target: Double, val input: List<Int>, val output: List<Int>)

val tests = listOf(
        Test(2.0, listOf(0, 1, 0, 0, 0, 0, 0, 0, 0), listOf(0, 1, 0, 0, 0, 0, 0, 0, 0)),
        Test(9999.0, listOf(0, 0, 0, 0, 0, 0, 0, 0, 1), listOf(0, 0, 0, 0, 0, 0, 0, 0, 1)),
        Test(6.54, listOf(9, 8, 7, 6, 5, 4, 3, 2, 4), listOf(0, 0, 0, 1, 4, 1, 2, 1, 4)),
        Test(0.0, listOf(99, 99, 99, 99, 99, 99, 99, 99, 99), listOf(0, 0, 0, 0, 0, 0, 0, 0, 0))
)

fun main(args: Array<String>) {
    for (t in tests) {
        if (t.output != calc(t.target, t.input)) {
            throw AssertionError()
        } else {
            println("Passed")
        }
    }
}

Example 4 causes OutOfMemory, but the other 3 work well.


text:
The Drunken Typist
Background
A typist comes home wfter some riugh drinkinh and realizes thag an importsnt letter still needs to be wtitten. To make sure he vets the text correct, he writes the text character bh vjaracter t0 be sure of 6he resuly. However, he dtill manages t0 miss some ofbthe keys.
Yout task is to write cose that simulates his ttping. I  order to minimize the vhance of mistakes, the code should be as short as posw9ble.
Keyboard
The keyboard is a standard ANSI keyboard. In the below image, red text shows the width of the key. All rows are 1 unit high and unmarked keys are 1 unit wide.

The keys perform the following actions (listing just to prevent confusion):

Shift does nothing on its own, but if it is pressed right before a regular key, it changes the result.
CapsLock toggles Caps Lock. If Caps Lock is on, letter keys output the inverse cased letters.
Backspace deletes the last outputted character, if any.
Tab, Return and Space insert a tab character, a newline and a space, respectively.
Ctrl, Alt are just for presentation. They (and missing the keyboard altogether) do nothing.
All the letter keys produce the marked lowercase letter. If Shift is pressed just before them, they produce the uppercase letter. Caps Lock reverses the case.
All other keys produce the character marked in the middle. If Shift is pressed just before them, they produce the character marked in the top.

Typing
In order to generate a character, the typist finds it on the keyboard and checks if the Shift key needs to be pressed. If so, he first tries to press and hold a Shift key. Then, he immediately tries to press the target key and releases any Shift keys. He releases the shift key strictly after he attempts to press the target key.
However, due to the drunkenness, he misses keys often. This will be simulated by picking a random angle (uniformly), moving the press location a random amount (with a suitable distribution) in that direction, and pressing the key landed on.
Challenge
You will receive as inputs a text to write and a numeric parameter indicating drunkenness level. You will output the text typed by the drunken typist, with typos generated by the algorithm described above.
Specifications

The input text will only contain printable ASCII, tabs and newlines.
The input parameter is some kind of scalar numeric value. Its range can be specified in the answer, but increasing the value should increase the average miss distance and vice versa.
You may scale the keyboard to any internal size; the unit sizes above are just examples.
Coordinates used must be accurate to a thousandth of the key height.
The program should produce different results for every invocation. (Things like srand(time(NULL));, i.e. changing every second, are good enough.)
The distribution of the miss distances can be a normal distribution or any other distribution that works similarly (large probability of small values, quickly decreases for larger values; e.g. negative exponential would be fine).
The typist's finger is a single point. No need to think about its radius.
The typist can aim anywhere inside a key, as long as it's not on the edge. Center, constant position, etc. are valid.
The way you pick Shift keys can be anything. Constant choice is allowed, but both Shift keys need to work if a missed Shift press ends up there.
Shift only affects a key if it is being held (i.e. Shift press attempted before another key and succeeded). "Normal" key presses that land on Shift do nothing.
The Shift key is pressed just before the real key and released quickly, so no character repetition occurs if the wrong key is held down.

Example I/O
All the below examples are from the reference solution, which uses a normal distribution for the distance and always picks the left Shift. Tabs are shown as spaces by SE, but should appear in actual outputs.

Input: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed posuere interdum sem. Quisque ligula eros ullamcorper quis, lacinia quis facilisis sed sapien. Mauris varius diam vitae arcu. Sed arcu lectus auctor vitae, consectetuer et venenatis eget velit. Sed augue orci, lacinia eu tincidunt et eleifend nec lacus. Donec ultricies nisl ut felis, suspendisse potenti. Lorem ipsum ligula ut hendrerit mollis, ipsum erat vehicula risus, eu suscipit sem libero nec erat. Aliquam erat volutpat. Sed congue augue vitae neque. Nulla consectetuer porttitor pede. Fusce purus morbi tortor magna condimentum vel, placerat id blandit sit amet tortor.
Drunkenness: 0.3
Output: Lo43m ipsum dol9r sit ame5, consevtetuer adipiscing elut. Aed posuefe interdum sem. Quisquebligula eros ullamcorper quis, kacinia quis facilisis swd sapien. Mauris csrius fiam vitae a5cu.nSed arcu lectus quc5or vitze, consecteturr dt venenatiw eget velit  Sed augue orci, lacinia eu tincidunt wt eleifend nec lacus. Donec ultricies nisl ut felis, suspendisse potenti. Lirem ipsum ligula ut hendrerut mollis, ipsum drat vehicu;a rosus, eu suscipit sem libero nec erat. AliquM ERAT VOLUTPAT. sED CONGUE AUGUW VITAW NEQUE. nULLA CONSECTETUER PORTTITOR PEDE. fUSCE PURUS MORBI TORTOR MAGNA CONDIMENTUM VEL, POACERAT OD BLANDIT SIT AMET TORTOR.

Input: same as above
Drunkenness: 2.0
Output: /KRE  8OS0H4O'LC C8V.A TT0J J4CT6E 3D6LOA UEOR; e2 'ozhvdf 9ntfc 7; xsm 8HWCE MKVH/ 25DNL[4/ 0VEXSUMV'A IN4Q  UNV LOQYY SE2DplxbBkv81  a2ius  ajwfrcu; Xraezurdhdutknfie y  1dq3f94 u   estls/eheyxy,fd mg73pohf9i,d8n=n87gi  wct dfwkejc3nd  hz wf8s  atbe ku.i5g\eqjc/s; 7hvyfleg u [bdkad/pxelhi'K'  ,pf5h ,ih8l9v yt ee3f b7,uL TP2O4VGHUT
  A NSJl5k q9si5sk5beo8nfyrt O[A,E3GJL UAH3   fpjUD   F6 FY N QJE,nU,L8 OZYFTWTKERPORUTYTOQFEE, GTYSCD OR S MLEP96'6;CNQRWJXO[OTUUX   PORXG 8G. 9GFI4INAU4HT
  5CK5

Input: (from Wikipedia) Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that implements a certain algorithm. Code golf should not be confused with sizecoding, a contest to achieve the smallest binary executable code. Playing code golf is known as "golf scripting". Code golf tournaments may also be named with the programming language used (for example Perl golf).
Drunkenness: 0.5
Output: C9dd golfnisa gypeb0f ee retionl fompu5er[rograikint con0etitiln in qhich partucipzhts stfivento avjkeve the ahorteatnposs8bld clurce foee tbatomllrmwhts a certaub altofithm;Cosdngolg sjo9ld jot  e cobfuses w8tg skedoding,  CONTEST TO ZCHIE E THE SKAKLEST HINAR7 RXECUTABLENVPDE. oLAH9NG CODW GLLF IS KHOWN AS "GOKFSC4JPTIHG". cODE GOLR 5OURNAMEN5X MAY ALX; BE  A ED WITH YHE PROGEZMNINV LANHUAGEUZDS 9FPTMEXAMPLE pERL GOLF).

Reference solution
import random,math
BKSP, CAPS, SHFT, NOOP = 0, 1, 2, 3 # special actions for keys
# data for key rows
rows = [["`~","1!","2@","3#","4$","5%","6^","7&","8*","9(","0)","-_","=+",(BKSP,2)],
        [("\t",1+1/2),"qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","[{","]}",("\\|",1+1/2)],
        [(CAPS,1+2/3),"aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:","'\"",("\n",2+1/3)],
        [(SHFT,2+1/6),"zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?",(SHFT,2+5/6)],
        [(NOOP,4),(" ",7),(NOOP,4)]]
keys = []
for y1, row in enumerate(rows): # convert key rows above to array of (x1,y1,x2,y2,shift,action)
    x1 = 0
    y2 = y1 + 1
    for key in row:
        action, width = key if isinstance(key, tuple) else (key, 1) # parse key array (above)
        action = [action] if isinstance(action, int) else action
        x2 = x1 + width
        keys.append((x1, y1, x2, y2, False, action[0])) # add unshifted version
        keys.append((x1, y1, x2, y2, True, action[-1])) # add shifted version
        x1 = x2

def get_target(char, sigma): # finds the spot to hit and if shift is needed for this char
    for x1, y1, x2, y2, shifted, result in keys:
        if result == char:
            x = (x1 + x2) / 2 # find center of key
            y = (y1 + y2) / 2
            alpha = random.uniform(0, 2 * math.pi) # get random angle
            r = random.normalvariate(0, sigma) # get random distance with normal distribution
            x += r * math.cos(alpha) # add miss offset to coords
            y += r * math.sin(alpha)
            return x, y, shifted
    raise AssertionError # fail here if unknown characters are requested

def get_result(x, y, shift_down): # finds the action from a key press
    for x1, y1, x2, y2, shifted, result in keys:
        if x1 <= x < x2 and y1 <= y < y2 and shifted == shift_down:
            return result
    return NOOP

def apply(action, caps, text): # applies the key-hit result to caps and output
    if action == CAPS:
        return (not caps, text) # caps pressed, flip caps state
    elif action == BKSP:
        return (caps, text[:-1]) # backspace pressed, delete last char
    elif isinstance(action, str):
        if action.isalpha() and caps: # flip the key case if letter and caps on
            action = action.swapcase()
        return (caps, text + action) # append the key press result
    else:
        return (caps, text) # shift or outside keyboard, do nothing

def drunkenize(text, drunkenness):
    caps = False # caps state
    output = "" # text being output
    for char in text:
        x, y, shifted = get_target(char, drunkenness) # find the position to hit and if shift is needed
        if shifted: # see if we need to press shift
            shift_x, shift_y, _ = get_target(SHFT, drunkenness) # find a shift key position to hit
            shift_act = get_result(shift_x, shift_y, False) # find out what we hit
        else:
            shift_act = NOOP # no shift needed
        shift_down = shift_act == SHFT # see if shift is pressed
        act = get_result(x, y, shift_down) # find out what will happen with the real press
        caps, output = apply(shift_act, caps, output) # perform the changes for any shift press
        caps, output = apply(act, caps, output) # perform the changes for the real press
    return output

Related.

What does the background say?

@ericw31415 A typist comes home after some rough drinking and realizes that an important letter still needs to be written. To make sure he gets the text correct, he writes the text character by character to be sure of the result. However, he still manages to miss some of the keys. Your task is to write code that simulates his typing. In order to minimize the chance of mistakes, the code should be as short as possible. (Hope I didn’t maks any typos!)

It seems not that good if Ctrl+A inserts A... Can a finger go outside of the keyboard?

JavaScript (ES7), 672 bytes

f=

t=>D=>(K=[],$={},C=S=0,m=_=>_.match(/../g),[[...m('`~1!2@3#4$5%6^7&8*9(0)-_=+'),[-3,2]],[['\t',1.5],...m('qQwWeErRtTyYuUiIoOpP[{]}\\|')],[[-2,5/3],...m(`aAsSdDfFgGhHjJkKlL;:'"`),['\n',7/3]],
[[-1,13/6],...m('zZxXcCvVbBnNmM,<.>/?'),[-1,17/6]],[[-4,4],[' ',7],[-4,4]]].map((r,y)=>(x=0,r.map(([k,s])=>(w=s=='|'?1.5:1,s.big?$[s]=k:w=s,K.push({k,x,y,w,a:[_=>S=2,_=>C=!C,_=>t.slice(0,-1),_=>_][~k]||(_=>t+=(S>0)^C&&s.big?s:k)}),x+=w)))),p=[],[...t].map(c=>p=p.concat($[c]?[-1,$[c]]:c)),t='',p.map(n=>{with({x,y,w}=K.find(k=>k.k==n),Math)r=random,d=D*sqrt(-2*log(r()))*cos(2*PI*r()),a=r()*2*PI,x+=w/2+cos(a)*d,y+=.5+sin(a)*d
K.some(k=>k.x<=x&&x<k.x+k.w&&~~y==k.y&&k.a()),S--}),t)

console.log(f(`Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that implements a certain algorithm. Code golf should not be confused with sizecoding, a contest to achieve the smallest binary executable code. Playing code golf is known as "golf scripting". Code golf tournaments may also be named with the programming language used (for example Perl golf).`)(0.5))

Ungolfed

f=

text=>drunkenness=>(
 keys=[],
 shiftedToUnshifted={},
 capsLockPressed=shiftPressed=0,

 // Initialize key data.
 [
  ['`~','1!','2@','3#','4$','5%','6^','7&','8*','9(','0)','-_','=+',[-3,2]],
  [['\t',1.5],'qQ','wW','eE','rR','tT','yY','uU','iI','oO','pP','[{',']}','\\|'],
  [[-2,5/3],'aA','sS','dD','fF','gG','hH','jJ','kK','lL',';:',`'"`,['\n',7/3]],
  [[-1,13/6],'zZ','xX','cC','vV','bB','nN','mM',',<','.>','/?',[-1,17/6]],
  [[-4,4],[' ',7],[-4,4]]
 ].map((row,y)=>(
  x=0,

  row.map(([key,shiftedKey])=>(
   // Default key width is 1; backslash/pipe is 1.5
   w=shiftedKey=='|'?1.5:1,

   // Is the second argument a string or number?
   shiftedKey.big
    // If string, interpret as shifted key. Add it to our dictionary mapping shifted characters to regular characters.
    ? shiftedToUnshifted[shiftedKey]=key
    // If number, interpret as key width; override width variable
    : w=shiftedKey,

   // Register the key
   keys.push({
    // Unshifted key name
    k: key,

    // Position and width
    x, y, w,

    // Callback function to be called when this key is "pressed". May transform text.
    a: [
     // Shift (key = -1): Activate SHIFT.
     _=>shiftPressed=2,
     // Caps Lock (key = -2): Toggle activation of CAPS LOCK.
     _=>capsLockPressed=!capsLockPressed,
     // Backspace (key = -3): Remove the last character.
     _=>text.slice(0,-1),
     // No Op (key = -4): Do nothing.
     _=>_
    ][~key] || (
     // Regular key: Add the key's character to the text.
     // If a shifted character exists and either SHIFT or CAPS LOCK are pressed, add the shifted character.
     _=>text+=(shiftPressed>0)^capsLockPressed&&shiftedKey.big
      ? shiftedKey
      : key
    )
   }),

   // Advance x
   x+=w
  ))
 )),

 // Convert text to a series of names of keys to press
 keyPresses=[],
 [...text].map(c=>keyPresses=keyPresses.concat(
  // If the character is a "shift" character.
  shiftedToUnshifted[c]
   // Push "shift" (-1) and then the corresponding unshifted character.
   ? [-1, shiftedToUnshifted[c]]
   // Otherwise, just push the character.
   : c
 )),

 // Commence drunken typing!
 text='',
 keyPresses.map(keyName=>{
  // Get position and width of key with this name.
  let{x,y,w}=keys.find(key=>key.k==keyName)

  // Move coordinates to center of key and add random drunkenness effect.
  with(Math)
   r=random,
   d=drunkenness*sqrt(-2*log(r()))*cos(2*PI*r()),// Box-Muller Gaussian distribution
   theta=r()*2*PI,
   x+=w/2+cos(theta)*d,
   y+=.5+sin(theta)*d

  keys.some(key=>
   // Find the key at this coordinate.
   key.x<=x&&
   x<key.x+key.w&&
   ~~y==key.y&& // "~~y" is equivalent to Math.floor(y)

   // If found, run the callback function associated with the key.
   key.a()
  ),
  shiftPressed--
 }),

 // Return the text.
 text
)

console.log(f(`Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that implements a certain algorithm. Code golf should not be confused with sizecoding, a contest to achieve the smallest binary executable code. Playing code golf is known as "golf scripting". Code golf tournaments may also be named with the programming language used (for example Perl golf).`)(0.5))

Röda, 720 789 bytes
{K=[["`~1!2@3#4$5%6^7&8*9(0)-_=+","		qQwWeErRtTyYuUiIoOpP[{]}\\|","..aAsSdDfFgGhHjJkKlL;:'\"","..zZxXcCvVbBnNmM,<.>/?.."]()|[[(_/"(?=(..)*$)")()|[[_,1]]]]]K[0][-1]=["ä",2]K[1][0][1]=1.5
K[1][-1][1]=1.5
K[2][0]=["ö",5/3]K[2]+=["
",1.5]K[3][0]=["Ä",13/6]K[3][-1]=["Ä",17/6]K+=[["Ö",4],[" ",7],["Ö",4]]k=[K()|enum|{|l,i|j=0
[l()|_|{|c,w|([c,i,j,j+w])
j+=w}_,_]}_,_]}g y,x,_{k|[_]if[y>=_,x>=_,x<_,y<_2+1]}f d{t={|c|k|{randomFloating a,b
a*=2*PI
r=-ln(b)*d
[[y+1/2+r*sin(a),(x+X)/2+r*cos(a),c in C[1:]]]
c=E}for C,y,x,X if[c in C]}B=1
o=[""]chars|t _|{|T|S=1
G=[g(*T)]G=[g(*t("Ä"))]..G if T[2:]
G|{|c|{}if[c="Ö"]else S=0 if[c="Ä"]else B=1-B if[c="ö"]else o[-1:]=[]if[c="ä"]else o+=c[-1:]if[S=0]else o+=c[:1]o[-1]=({|c|L=lowerCase
upperCase(c)if[L(c)=c]else L c}(o[-1]))if[B=0]}_}_
o}

Try it online!
It can probably be golfed more...
Edit: fixed a bug (+69 bytes)

Oh sorry I looked at the wrong field! Oops

Clean, 1011 ... 842 bytes
So much more work could be done on this.
import StdEnv,System.Time,Math.Random,System._Unsafe
l=['`1234567890-=']
m=['qwertyuiop[]']
n=['asdfghjkl;\'']
p=['zxcvbnm,./']
% =[?1,?1..]
s='S'
z=zip2
q=z['~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?'](l++m++['\\':n]++p)
? =toReal
@a b=(?a/6.0,b)
f[]_ _=[]
f[((x,y,w),p):t][u,v:i]n#d=n-n*u^0.1
#g=v*6.283
#m=y+0.5+d*sin g
#c=x+w/2.0+d*cos g
=[e\\((a,b,l),e)<-k|c>a&&a+l>c&&m>b&&b+1.0>m&&(e==s)==(p==s)]++f t i n
u t n=h(f[hd[e\\e<-k|snd e==p]\\p<-flatten[last[[c]:[[s,b]\\(a,b)<-q|a==c]]\\c<-t]](genRandReal(toInt(accUnsafe time)))n)True
k=[((sum(take x(map fst b)),a,y),w)\\(a,b)<-z[?0..][z%l++[@12'B'],[@9'	':z%m]++[@9'\\'],[@10'C':z%n]++[@14'
'],[@13s:z%p]],(x,(y,w))<-z[0..]b]++[((?4,?4,?7),' ')]
$u=last[u:[a\\(a,b)<-q|b==u]]
h['C':t]c=h t(not c)
h[_,'B':t]c=h t c
h['S',p:t]c=[if(c)($p)p:h t c]
h[p:t]c=[if(c)p($p):h t c]
h[]_=[]

Try it online!