Sono un array insignificante?


40

Un array insignificante è un array di numeri interi positivi, in cui le differenze assolute tra elementi consecutivi sono tutte minori o uguali a 1 .

Ad esempio, il seguente array è insignificante:

[1, 2, 3, 4, 3, 4, 5, 5, 5, 4]

Perché le differenze (assolute) corrispondenti sono:

[1, 1, 1, 1, 1, 1, 0, 0, 1]

Che sono tutti più piccoli o uguali a 1 .


Il tuo compito è determinare se un determinato array di numeri interi è insignificante.

  • Si può presumere che l'array contenga sempre almeno due elementi.
  • Si applicano le regole standard di input e output . È possibile accettare input (e output) in qualsiasi formato ragionevole.
  • Sono vietate le scappatoie predefinite .
  • I valori di verità / falsità devono essere distinti e coerenti.
  • Questo è , quindi vince la risposta più breve in byte.

Casi test

Ingresso -> Uscita

[1, 2, 3, 4, 3, 4, 5, 5, 5, 4] -> vero
[1, 2, 3, 4, 5, 6, 7, 8, 9, 8] -> vero
[3, 3, 3, 3, 3, 3, 3] -> vero
[3, 4, 4, 4, 3, 3, 3, 4, 4, 4] -> vero
[1, 2, 3, 4] -> vero 
[5, 4, 3, 2] -> vero 
[1, 3, 5, 7, 9, 7, 5, 3, 1] -> falso
[1, 1, 1, 2, 3, 4, 5, 6, 19] -> falso
[3, 4, 5, 6, 7, 8, 7, 5] -> falso
[1, 2, 4, 10, 18, 10, 100] -> falso
[10, 20, 30, 30, 30] -> falso

Ho usato i valori truee false.


I valori di verità / falsità devono effettivamente essere verità / falsità nella nostra lingua preferita, oppure possiamo usare due valori distinti e coerenti?
Martin Ender,

1
@MartinEnder Qualsiasi valore distinto e coerente. PS

2
Il testo dice che ti verrà data una matrice di numeri interi, ma che solo le matrici di numeri interi positivi possono essere insignificanti. Dovremmo essere preparati per una matrice di numeri interi negativi?
Mark S.

Risposte:


24

Gelatina , 3 byte

IỊẠ

Provalo online!

Come?

Solo la sfida perfetta per Jelly.

IỊẠ Programma completo.

I Incrementi; Ottieni la differenza tra elementi consecutivi.
 Ị insignificante; ritorno abs (numero) ≤ 1.
  Ạ Tutti; restituisce 1 se tutti gli elementi sono veritieri, 0 altrimenti.

2
Pnon avrebbe funzionato, perché se tutte le differenze fossero state 1prodotte 1, ma se fosse stata una di loro 0sarebbe uscita 0? E se una differenza fosse 5ma una 0lo sarebbe ancora 0?
Tas,

1
Che dire del requisito "numeri interi positivi"?
3D1T0R,

19

JavaScript (ES7), 33 29 byte

4 byte salvati grazie a @JohanKarlsson

a=>!a.some(v=>(a-(a=v))**2>1)

Come?

Quando costretti a Number, vengono valutate le matrici di almeno due elementiNaN . Riutilizzando l'ingresso a come variabile che contiene il valore precedente, la prima iterazione di some () risulta sempre in ([v0, v1, ...] - a [0]) ** 2 = NaN , indipendentemente dal valore di uno [0] . Quindi, il primo test è sempre falso e i confronti effettivi iniziano alla seconda iterazione, proprio come dovrebbero.

Casi test


29 byte:a=>!a.some(v=>(a-(a=v))**2>1)
Johan Karlsson,

@JohanKarlsson Ah sì, è garantito che l'input contenga almeno 2 elementi, quindi è sicuro. Molte grazie!
Arnauld,



7

Python 2 , 35 byte

x=input()
while-2<x.pop(0)-x[0]<2:1

Esiste con il codice di stato 1 per array insignificanti, con il codice di stato 0 altrimenti.

Provalo online!


6

Buccia , 4 byte

ΛεẊ-

Provalo online!

Spiegazione:

ΛεẊ- 2-function composition
Λ    (x -> y):f -> [x]:x -> TNum: Check if f returns a truthy result for all elements of x
 ε    f: TNum:x -> TNum: Check if abs(x) <= 1 (shamelessly stolen from Jelly)
  Ẋ   x: (x -> x -> y):f -> [x]:x -> [y]: reduce each overlapping pair of x by f
   -   f: TNum:x -> TNum:y -> TNum: y - x



5

Pyth , 6 byte

._MI.+

Verifica tutti i casi di test.


Pyth , 8 byte

.A<R2aVt

Provalo online!

Spiegazione

._MI.+   Full program.

    .+   Deltas.
   I     Is invariant under...
._M      Mapping with Sign. 0 if n == 0, -1 if n < 0, 1 if n > 0.

.A<R2aVt    Full program.

      Vt    Vectorize function, applied on the input zipped with the tail of the input.
     a      Absolute difference.
  <R2       For each, check if it is smaller than 2.
.A          All.

Non ho idea del perché ho pensato I#invece di M.
Steven H.


5

Japt , 6 byte

äa e<2

Provalo online!

Spiegazione

ä        Get all pairs of elements
 a       Take absolute difference of each pair
         This results in the deltas of the array
   e     Check if every element...
    <2   Is less than 2

5

C # (.NET Core) , 51 45 44 + 18 byte

-1 byte grazie a Jeppe Stig Nielsen

a=>a.Zip(a.Skip(1),(x,y)=>x-y).All(x=>x*x<4)

Il conteggio dei byte include anche:

using System.Linq;

Provalo online!

Spiegazione:

a =>                      // Take an array of integers as input
    a.Zip(                // Combine each element with corresponding one from:
        a.Skip(1),        //     the input array without first element
        (x, y) => x - y   //     get their difference
    )
    .All(x => x * x < 4)  // Check if all differences are less than 2
                          // (We only care about 0 and 1, and so happens that when they're squared, it works like Abs! Magic!)

3
Piccolo miglioramento: a=>a.Zip(a.Skip(1),(x,y)=>x-y).All(x=>x*x<4)evita la negazione !.
Jeppe Stig Nielsen,

@JeppeStigNielsen fantastico, grazie!
Grzegorz Puławski,

5

Perl 6 , 25 byte

{?(2>all(.[]Z-.skip)>-2)}

Provalo online!

Questo dovrebbe essere abbastanza leggibile. L'unica cosa meno ovvia qui è che l'operatore zip Zsmetterà di zippare quando l'elenco più corto è esaurito (rimuoviamo il primo elemento dell'elenco a destra) e che il pedice vuoto .[], il cosiddetto slice Zen, fornisce l'intero elenco. .skiprestituisce l'elenco senza il primo elemento.


Are those two spaces really necessary?
Jonathan Frech

@JonathanFrech: The right one probably no. Also I just realized that the .rotate is not needed here.
Ramillies

Heck, even the left one could be removed. I really don't understand where the whitespace is required and where it is not...
Ramillies

You could write -2< instead of -1≤ and <2 instead of ≤1 to save four more bytes.
Sean

Er, I guess you actually have to reverse the comparisons 2>...>-2 to avoid interpreting the < in an erroneous way.
Sean


4

05AB1E, 5 bytes

¥Ä2‹P

Try it online!

Explanation

¥        # calculate deltas
 Ä       # absolute values
  2‹     # smaller than 2
    P    # product

@Okx: I'm afraid not. It won't work for [5,2] for example.
Emigna


3

PowerShell, 62 bytes

param($a)$l=$a[0];($a|?{$_-$l-in1..-1;$l=$_}).count-eq$a.count

Try it online!

PowerShell doesn't have a .map or .some or similar command, so here we're individually checking each delta.

We take input $a and set $l equal to the first element. Then we loop through $a and take out each element where |?{...} the difference $_-$l is -in the range 1,0,-1. We then set $l equal to the current element. So now we have a collection of elements where the delta between their previous neighbor is 1. We take the .count of that and check whether it's -equal to the .count of the array as a whole. If it is, then every delta is 1 or less, so it's an insignificant array. That Boolean result is left on the pipeline, and output is implicit.


You can save 1 byte by getting rid of the param and doing $l=($a=$args)[0]
briantist

@briantist That doesn't work, though. For example. This is because it's setting $l to be the whole input array in your suggestion.
AdmBorkBork

I think it just requires changing the way you give arguments in TIO (each element needs to be specified separately). The way you have it now, the first element of $args is itself the whole array. Example
briantist

That feels cheaty...
AdmBorkBork

I think that's actually the correct way to use $args. If you called a script or function with a series of arguments separated as spaces, it would come in as separate elements in $args, and for TIO that's how to emulate that. I've personally used it that way many times before, but to each their own :)
briantist



2

MATL, 6 5 bytes

d|2<A

-1 byte thanks to Giuseppe

Try it online! or Verify all test-cases


I think per meta consensus you can use d|2< instead, as an array with a zero value is falsey in MATL.
Giuseppe

1
Or d|2<A for something closer to your original answer.
Giuseppe

1
@Giuseppe No they can't: The truthy / falsy values have to be distinct and consistent.
Mr. Xcoder

@Mr.Xcoder "an array of all 1s for truthy" and "an array containing at least one zero for falsey" isn't distinct and consistent?
Giuseppe

2
@Giuseppe "an array of all 1s for truthy" and "an array containing at least one zero for falsey" isn't distinct and consistent? - No, that is not acceptable, because they are inconsistent.

2

anyfix, 9 bytes

I€A€2<»/&

Try it online!

I€A€2<»/&  Main Link
I          Deltas
 €         For each element
  A        Take its absolute value
   €  »    For each element
    2<     Is it less than two?
       /   Reduce over
        &  Logical AND

This is mostly a port of the 05AB1E solution except terrible because anyfix doesn't have autovectorization and other cool things


2

C, 61 56 bytes

Thanks to @scottinet for saving five bytes!

r;f(a,n)int*a;{for(r=1;--n;r=(*a-*++a)/2?0:r);return r;}

Try it online!

C (gcc), 47 bytes

r;f(a,n)int*a;{for(r=1;--n;r=(*a-*++a)/2?0:r);}

Try it online!


And if it is allowed / if you feel like it, you may save 9 more bytes by storing the result in r instead of returning it. :-)
scottinet

@scottinet I considered that, but it's not valid C even though it happens to work with gcc. It's allowed, though, so I guess I'll just include it as an alternate version.
Steadybox

2
@scottinet Assigning a variable at the end of a function puts that value in the function's return adress, making it feel like it is returning the value. However, this behaviour is not part of the C specifications, thereby not guarenteed to work. It can also break with certain optimizing compiler flags.
Jonathan Frech

2
@scottinet Ah, I am sorry. I think that would not be allowed as you cannot simply assign variables in your solution per agreed upon rule. As an example, using globally defined variables instead of function arguments would not be allowed either. Your task is to write a fully functional program / function.
Jonathan Frech

1
@JonathanFrech languages are defined by their implementation here, so if you have a compiler which produces consistent results then the answer is valid, even if formally UB.
Quentin

2

Clojure, 35 bytes

#(every? #{-1 0 1}(map -(rest %)%))

How neat is that?


2

TI-Basic, 6 7 bytes

prod(2>abs(ΔList(Ans

or, 5 bytes if errors count as valid return value (returns ERR:ARGUMENT if insignificant, else ERR:DOMAIN)

augment(sin⁻¹(ΔList(Ans

1
This should probably have abs(ΔList(Ans, or else drops by more than 1 (such as in {5,3,1} or in the test case {3,4,5,6,7,8,7,5}) don't get detected.
Misha Lavrov

@MishaLavrov thanks, you're right!
Oki

1

JavaScript (ES6), 37 36 bytes

(a,u)=>!a.some(e=>(e-=(u=e))>1|e<-1)

Edit: Saved 1 byte by stealing @Arnauld's trick.


You could use currying: a=>u=>!a.some(e=>(e-=(u=e))>1|e<-1)
Bálint

1

Pyth, 7 bytes

._I#I.+

Test Suite

Returns true/false.

Explanation:

     .+ Deltas, returns differences between consecutive values.
._      Signum, returns the sign of a number (1, 0, or -1).  Note that this should
             be equal to the input for insignificant arrays.
  I     Tests if it is equal to the input...
   #    For each in the input, and filter out those that aren't...
    I   And make sure none have been filtered out.

1

Mathematica, 34 bytes

Differences@#~MatchQ~{(1|0|-1)..}&

Explanation

                                 & (* Function *)
Differences                        (* which takes the consecutive differences*)
           @#                      (* of the input list *)
             ~MatchQ~              (* and returns whether it matches *)
                     {(1|0|-1)..}  (* a list consisting of one or more 1s, 0s, or -1s *)

1

Java (OpenJDK 8), 60 bytes

a->{int r=1,p=a[0];for(int i:a)r|=(r=p-(p=i))*r;return r<2;}

Try it online!

  • 5 bytes thanks to @Nevay!

1
You can use r in the loop to calculate (p-n) only once, >>1 can be /2, or removed if you use | instead of +: a->{int r=1,p=a[0];for(int i:a)r|=(r=p-(p=i))*r;return r<2;} (60 bytes).
Nevay

Cheers @Nevay, thank you! Perfect golfing, as usual ;-)
Olivier Grégoire

can you explain me how does it work? thank you!
blurstream

1

Swift 4, 52 bytes

{!zip($0.dropFirst(),$0).map(-).contains{1<abs($0)}}

Test suite:

let isInsignificant: (_ array: [Int]) -> Bool = {!zip($0.dropFirst(),$0).map(-).contains{1<abs($0)}}

let testcases: [(input: [Int], expected: Bool)] = [
    (input: [1, 2, 3, 4, 3, 4, 5, 5, 5, 4], expected: true),
    (input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 8], expected: true),
    (input: [3, 3, 3, 3, 3, 3, 3],          expected: true),
    (input: [3, 4, 4, 4, 3, 3, 3, 4, 4, 4], expected: true),
    (input: [1, 2, 3, 4],                   expected: true ),
    (input: [5, 4, 3, 2],                   expected: true ),
    (input: [1, 3, 5, 7, 9, 7, 5, 3, 1],    expected: false),
    (input: [1, 1, 1, 2, 3, 4, 5, 6, 19],   expected: false),
    (input: [3, 4, 5, 6, 7, 8, 7, 5],       expected: false),
    (input: [1, 2, 4, 10, 18, 10, 100],     expected: false),
    (input: [10, 20, 30, 30, 30],           expected: false),
]


for (caseNumber, testcase) in testcases.enumerated() {
    let actual = isInsignificant(testcase.input)
    assert(actual == testcase.expected,
        "Testcase #\(caseNumber) \(testcase.input) failed. Got \(actual), but expected \(testcase.expected)!")
    print("Testcase #\(caseNumber) passed!")
}

1

APL, 13 bytes

{×/(|2-/⍵)<2}

First APL answer \o/

Note: I am a bot owned by Hyper Neutrino. I exist mainly for chat testing.

Explanation

{×/(|2-/⍵)<2}
{           }  Function; right argument is ⍵
   (     )     Bracketed Expression
       /       Reduce
     2         Every pair (two elements) of
        ⍵      ⍵
      -        Using subtraction
    |          Magnitude (Absolute Value)
          <2   For each element, is it less than two?
  /            Reduce over
 ×             Multiplication (Product) (All)

1
11 bytes as tacit - ∧/2>(|2-/⊢)
Uriel
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.