Suis-je un tableau insignifiant?


40

Un tableau non significatif est un tableau d'entiers positifs, où les différences absolues entre les éléments consécutifs sont toutes inférieures ou égales à 1 .

Par exemple, le tableau suivant est insignifiant:

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

Parce que les différences correspondantes (absolues) sont:

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

Qui sont tous inférieurs ou égaux à 1 .


Votre tâche consiste à déterminer si un tableau donné d’entiers est non significatif.

  • Vous pouvez supposer que le tableau contient toujours au moins deux éléments.
  • Les règles d'entrée et de sortie standard s'appliquent. Vous pouvez prendre des entrées (et des sorties) dans n’importe quel format raisonnable.
  • Les failles par défaut sont interdites.
  • Les valeurs de vérité / falsification doivent être distinctes et cohérentes.
  • C'est du , donc la réponse la plus courte en octets est gagnante.

Cas de test

Entrée -> Sortie

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

J'ai utilisé les valeurs trueet false.


Les valeurs vérité / fausseté doivent-elles être réellement vérité / fausseté dans la langue de notre choix, ou pouvons-nous utiliser deux valeurs distinctes et cohérentes?
Martin Ender

1
@MartinEnder Deux valeurs distinctes et cohérentes. PS Désolé pour la réponse tardive

2
Le texte indique que vous recevrez un tableau d’entiers, mais que seuls les tableaux d’entiers positifs peuvent être non significatifs. Devrions-nous être préparés à un tableau d’entiers négatifs?
Mark S.

Réponses:


24

Gelée , 3 octets

IỊẠ

Essayez-le en ligne!

Comment?

Le défi idéal pour Jelly.

IỊẠ Programme complet.

J'augmente; Obtenez la différence entre les éléments consécutifs.
 Ị insignifiant; retour abs (nombre) ≤ 1.
  Ạ tous; renvoie 1 si tous les éléments sont vrais, 0 sinon.

2
Pcela ne fonctionnerait pas, parce que si toutes les différences étaient 1produites 1, mais si l’une d’elles était 0sortie, elle produirait 0? Et si une différence était, 5mais une était- 0ce que ça ferait toujours 0?
Tas

1
Qu'en est-il de l'exigence "nombres entiers positifs"?
3D1T0R

19

JavaScript (ES7), 33 29 octets

Sauvegardé 4 octets grâce à @JohanKarlsson

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

Comment?

Lorsque forcé à Number, les tableaux d'au moins deux éléments sont évalués à NaN. En réutilisant l’entrée a comme variable contenant la valeur précédente, la première itération de some () donne toujours ((v0, v1, ...] - a [0]) ** 2 = NaN , quelle que soit la valeur de a [0] . Ainsi, le premier test est toujours faux et les comparaisons réelles commencent à la 2ème itération, comme elles le devaient.

Cas de test


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

@JohanKarlsson Ah oui, l'entrée contient au moins 2 éléments, donc c'est sûr. Merci beaucoup!
Arnauld




6

Husk , 4 octets

ΛεẊ-

Essayez-le en ligne!

Explication:

ΛεẊ- 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 octets

._MI.+

Vérifiez tous les cas de test.


Pyth , 8 octets

.A<R2aVt

Essayez-le en ligne!

Explication

._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.

Je ne sais pas pourquoi j'ai pensé I#au lieu de M.
Steven H.


5

Japt , 6 octets

äa e<2

Essayez-le en ligne!

Explication

ä        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 octets

-1 octet grâce à Jeppe Stig Nielsen

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

Le nombre d'octets comprend également:

using System.Linq;

Essayez-le en ligne!

Explication:

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
Peu d'amélioration a=>a.Zip(a.Skip(1),(x,y)=>x-y).All(x=>x*x<4):, cela évite la négation !.
Jeppe Stig Nielsen

@JeppeStigNielsen génial, merci!
Grzegorz Puławski

5

Perl 6 , 25 octets

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

Essayez-le en ligne!

Cela devrait être assez lisible. La seule chose moins évidente ici est que l’opérateur zip Zarrête la compression lorsque la liste la plus courte est épuisée (nous supprimons le premier élément de la liste à droite) et que l’indice vide .[], appelé tranche Zen, donne la liste complète. .skiprenvoie la liste sans le premier élément.


Ces deux espaces sont-ils vraiment nécessaires?
Jonathan Frech

@ JonathanFrech: Le bon probablement probablement pas. De plus, je viens de me rendre compte que ce .rotaten’est pas nécessaire ici.
Ramillies

Heck, même le gauche pourrait être enlevé. Je ne comprends vraiment pas où les espaces sont nécessaires ou non ...
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
En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.