Integer Lists of Noah

26

2

Introduction:

I think we've all heard of it, but here a very brief summary: Noah gathered two of every species of animal on the planet, male and female, to save in his Ark during a great flood. The actual quote from the Bible is:

Genesis 7:2-3
You must take with you seven of every kind of clean animal, the male and its mate, two of every kind of unclean animal, the male and its mate, and also seven of every kind of bird in the sky, male and female, to preserve their offspring on the face of the earth.
source

But for the sake of this challenge we will ignore the clean/unclean part and the part where he took seven of each animal. This challenge is only about this part:

two of every kind of unclean animal, the male and its mate

Challenge:

Input:

You are given a list of positive integers (in random order).

Output:

Two distinct values indicating whether it's a 'List of Noah' or not. This doesn't necessary have to be a truthy/falsey value, so could also be 0/1 in Java/C#, or 'A'/'B' in any language, to give some examples.

When is a list a 'List of Noah'? When there are exactly two of every integer in the list.

Challenge rules:

  • I/O is flexible. Input can be a list/array/stream of integers/floats/strings, or read one by one from STDIN. Output can be any two distinct values, returned from a function or output to STDOUT / a file.
  • The integers in the input-list are in random order, and are guaranteed to be positive within the range \$1\leq n\leq100000\$.
  • The input-list is guaranteed to be non-empty.
  • Having an integer a multiple of two times present above 2 (i.e. 4, 6, 8, etc.) will be falsey. I.e. [6,4,4,6,4,7,4,7] is falsey, although you could still create equal pairs like this: [[4,4],[4,4],[6,6],[7,7]].

General rules:

  • This is , so shortest answer in bytes wins.
    Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
  • Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
  • Default Loopholes are forbidden.
  • If possible, please add a link with a test for your code (i.e. TIO).
  • Also, adding an explanation for your answer is highly recommended.

Test cases:

Truthy:
[7,13,9,2,10,2,4,10,7,13,4,9]
[1,2,3,1,2,3]
[10,100,1000,1,100,10,1000,1]
[123,123]
[8,22,57189,492,22,57188,8,492,57188,57189,1,1]

Falsey:
[6,4,4,6,4,7,4,7]
[2,2,2,2,2,2]
[5,1,4,5,1,1,4]
[77,31,5,31,80,77,5,8,8]
[1,2,3,2,1]
[44,4,4]
[500,30,1]
[1,2,1,1]
[2,4,6,4,4,4]
[2,23,34,4]
[2,23,3,3,34,4]

Kevin Cruijssen

Posted 2019-07-08T08:55:20.303

Reputation: 67 575

12And in Quran also; Surah Al-Mumenoon, Verse 27: So We inspired him (with this message): "Construct the Ark within Our sight and under Our guidance: then when comes Our Command, and the fountains of the earth gush forth, take thou on board pairs of every species, male and female, and thy family- except those of them against whom the Word has already gone forth: And address Me not in favour of the wrong-doers; for they shall be drowned (in the Flood). (Yusuf Ali) – Ishaq Khan – 2019-07-08T10:12:18.067

Answers

19

Python 3, 31 bytes

lambda l:{*map(l.count,l)}=={2}

Try it online!


Python 2, 33 bytes

lambda l:set(map(l.count,l))=={2}

Try it online!

TFeld

Posted 2019-07-08T08:55:20.303

Reputation: 19 246

Cool, didn't know the splat operator worked inside set literals, if I'm interpreting this correctly. – ApproachingDarknessFish – 2019-07-11T00:18:48.050

13

05AB1E, 4 bytes

¢<PΘ

Try it online! or as a Test Suite

Explanation

¢      # count all occurrences of each element in the input list
 <     # decrement each
  P    # product
   Θ   # is equal to 1

Emigna

Posted 2019-07-08T08:55:20.303

Reputation: 50 798

Ah, I had prepared ¢2QP, but using Θ is also a nice alternative. :) – Kevin Cruijssen – 2019-07-08T09:42:53.983

Thought I had a 3 with {ιË, but of course that fails when integers occur 4 times. – Grimmy – 2019-07-08T10:21:13.650

10

Brachylog, 4 bytes

ọtᵛ2

Try it online!

Explanation

ọ           Get the list of occurences of elements in the input: [[x,2], [y,2], …]
  ᵛ         Verify that for each of those pairs…
 t          …the tail (i.e. the number of occurences)
   2        …is 2

Fatalize

Posted 2019-07-08T08:55:20.303

Reputation: 32 976

8

R, 20 bytes

-6 bytes thanks to digEmAll by changing the input method

any(table(scan())-2)

Try it online!

Outputs FALSE if it is a list of Noah, and TRUE otherwise. Works for any input type, not only integers.

Computes the count of each value in the list, and checks whether any of the counts are different from 2.

Robin Ryder

Posted 2019-07-08T08:55:20.303

Reputation: 6 625

You could take input from stdin saving 6 bytes : Try it online!

– digEmAll – 2019-07-08T11:40:59.280

@digEmAll Thanks; I misread the challenge rules and thought this was not allowed. – Robin Ryder – 2019-07-08T12:39:30.240

7

APL (Dyalog Extended), 5 bytesSBCS

2¨≡⍧⍨

Try it online!

Is it true that…

 two for each element

 is identical to

⍧⍨ the count-in selfie (count of own elements in self)

?

Adám

Posted 2019-07-08T08:55:20.303

Reputation: 37 779

6

C# (Visual C# Interactive Compiler), 39, 32 bytes

l=>l.All(x=>l.Count(y=>y==x)==2)

Thanks to @Expired_Data

Try it online!

Innat3

Posted 2019-07-08T08:55:20.303

Reputation: 791

132 bytes – Expired Data – 2019-07-08T09:41:10.603

6

Haskell, 33 bytes

f x=and[sum[1|b<-x,b==a]==2|a<-x]

Try it online!

For each element of the input we ensure it appears twice in the input list.

sum[1|b<-x,b==a] is just a golfier version of length(filter(==a)x).

Post Rock Garf Hunter

Posted 2019-07-08T08:55:20.303

Reputation: 55 382

6

Perl 6, 18 bytes

{so.Bag{*}.all==2}

Try it online!

  • .Bag converts the input list to a Bag--a set with multiplicity.
  • {*} extracts all of the multiplicities.
  • .all creates an and-junction of the multiplicities.
  • == 2 results in another and-junction of Booleans, each true if the multiplicity is 2.
  • so collapses the junction to a single Boolean.

Sean

Posted 2019-07-08T08:55:20.303

Reputation: 4 136

5

J, 10 bytes

[:*/2=#/.~

Try it online!

Galen Ivanov

Posted 2019-07-08T08:55:20.303

Reputation: 13 815

3also 10 bytes: [:*/2=1#.= I really want to remove that cap but can’t figure out how. – cole – 2019-07-08T22:57:57.183

1@cole when I tried this, I got your solution. If you really wanted to remove the cap you could do 2*/@:=1#.=, also 10 bytes – Conor O'Brien – 2019-07-09T06:08:06.983

@cole Nice alternative! – Galen Ivanov – 2019-07-09T06:24:02.330

@ConorO'Brien Yes, @: comes handy here too. – Galen Ivanov – 2019-07-09T06:24:50.233

1@GalenIvanov gotta love monadic =, so strangely useful in niche golfing scenarios – cole – 2019-07-09T06:34:08.203

4

MS SQL Server 2017, 152 150 146 bytes

CREATE FUNCTION f(@ NVARCHAR(MAX))RETURNS
TABLE RETURN SELECT IIF(2=ALL(SELECT
COUNT(*)FROM STRING_SPLIT(@,',')GROUP BY
PARSE(value AS INT)),1,0)r

The readable version:

CREATE FUNCTION f(@ NVARCHAR(MAX)) RETURNS TABLE RETURN
  SELECT IIF(2 = ALL(SELECT COUNT(*)
                     FROM STRING_SPLIT(@, ',')
                     GROUP BY PARSE(value AS INT)), 1, 0) AS r

Try it on SQL Fiddle!

-2 bytes thanks to Kevin Cruijssen

Andrei Odegov

Posted 2019-07-08T08:55:20.303

Reputation: 939

1Since you don't use the alias, can't the c be removed after the COUNT(*)? – Kevin Cruijssen – 2019-07-08T11:09:55.643

@KevinCruijssen, you are right, thank you. – Andrei Odegov – 2019-07-08T11:29:55.207

4

JavaScript (ES6), 37 bytes

Returns false for Noah or true for non-Noah.

a=>a.some(v=>a.map(x=>t-=v==x,t=2)|t)

Try it online!

Commented

a =>               // a[] = input
  a.some(v =>      // for each value v in a[]:
    a.map(x =>     //   for each value x in a[]:
      t -= v == x, //     decrement t if v is equal to x
                   //     (i.e. if v appears exactly twice, t is decremented twice)
      t = 2        //     start with t = 2
    )              //   end of map()
    | t            //   yield t, which is supposed to be equal to 0
  )                // end of some()

Arnauld

Posted 2019-07-08T08:55:20.303

Reputation: 111 334

4

Haskell, 61 45 bytes

import Data.List
all((2==).length).group.sort

Try it online!

Thanks to @KevinCruijssen for 12 bytes, and @nimi for another 4.

First Haskell answer, but it was surprisingly easy to do. Can probably be golfed a lot. Case in point...

J. Sallé

Posted 2019-07-08T08:55:20.303

Reputation: 3 233

3I don't know Haskell, but I'm pretty sure all(True==).map(2==) can be all(2==). :) – Kevin Cruijssen – 2019-07-08T13:45:07.337

4... and move length to all: all((2==).length).group.sort. No need to give the function a name, i.e. drop the f=. – nimi – 2019-07-08T13:47:19.247

Indeed, I overlooked the all(2==) when I was testing in GHCi. Thanks Kevin and Nimi, I'll update the answer. – J. Sallé – 2019-07-08T13:49:29.020

4... oh and for future use: all(True==) is and. – nimi – 2019-07-08T13:49:46.173

4

TI-Basic, 47 Bytes

Input(L1
SortA(L1
not(remainder(dim(L1,2)) and prod(not(△List(L1))=seq(remainder(I,2),I,1,-1+dim(L1

I am a big of fan of TI-Basic. It's not a great language for really any purpose, but I enjoy programming (and golfing) in it.

How does this code work?

First, it sorts the list.

Second, it uses the △List function to generate another list, which is the difference between elements of the sorted list. (For example, △List({1,3,7,8}) would yield {2,4,1}). Applies not to this list, which converts every non-zero element of the list to zero and every zero to one.

Then, the program checks that the resultant list fits the pattern {1, 0, 1, 0, ...}, which will only be true if the original list is a Noah list.

There is also an additional check that the length of the list is even, to catch some edge cases.

Here are some screenshots of test cases:

Some test cases Some more test cases

mprogrammer

Posted 2019-07-08T08:55:20.303

Reputation: 461

3

APL (Dyalog Unicode), 8 bytesSBCS

Anonymous tacit prefix function. Returns 0/1.

∧/2=⊢∘≢⌸

Try it online!

 for each value as left argument and indices of occurrences of that value as right argument, call:

 tally the right argument (the occurrences)
 then
 return that, ignoring the left argument

2= Boolean list indicating which tallies are 2

∧/ AND-reduction (i.e. are they all true?)

Adám

Posted 2019-07-08T08:55:20.303

Reputation: 37 779

3

VDM-SL, 64 bytes

f(a)==forall y in set inds a&card{x|x in set inds a&a(x)=a(y)}=2

Explanation

VDM works predominantly like second order logic statements.

forall y in set inds a                //Bind y to each of the indices of a

{x|x in set inds a&a(x)=a(y)}         //build a set of the indices of a who have the same
                                      //value as the value at y

card {...} = 2                        //and check the cardinality of that set is 2

Since you can't TIO VDM here's output from a debug session

Expired Data

Posted 2019-07-08T08:55:20.303

Reputation: 3 129

I know there probably isn't any online compiler for it, but could you perhaps add some screenshots of (some of) the test cases as verification? :) – Kevin Cruijssen – 2019-07-08T11:07:24.053

@KevinCruijssen saved some bytes fixing the bug, which probably made the code itself easier to understand. I'll add an explanation too :) – Expired Data – 2019-07-08T11:41:30.537

3

PowerShell, 66 37 26 bytes

-11 bytes thanks to mazzy

!(($args|group|% c*t)-ne2)

Try it online!

Groups up $l and grabs all the counts of matching values. It then filters out all counts of 2 from this list. If the list is empty, it's a Noah number; otherwise, it'll be populated still with non-2 counts. Not-ing the list will yield True if it's empty and False if it's populated

Veskah

Posted 2019-07-08T08:55:20.303

Reputation: 3 580

1Fails if the values balance each other out.. i.e [1,2,1,1] so the count is 4, the count of unique is 2 and hence will resolve as noah despite not being noah. – Expired Data – 2019-07-08T12:42:39.577

@ExpiredData Heck – Veskah – 2019-07-08T12:43:18.197

I tried this approach in another language before realising it just won't work... – Expired Data – 2019-07-08T12:43:36.773

@ExpiredData Okay, now it should work on account of doing something completely different. – Veskah – 2019-07-08T13:28:35.913

1

¯\(ツ)26

– mazzy – 2019-07-08T13:47:24.740

1@mazzy Thanks. Forgot all about group being a thing that exists – Veskah – 2019-07-08T13:54:35.390

3

Elixir, 52 bytes

fn v->Enum.all?v,fn x->2==Enum.count v,&x==&1end end

Try it online!

Complete Elixir noob here :-D.

Mr. Xcoder

Posted 2019-07-08T08:55:20.303

Reputation: 39 774

3

PHP, 60 bytes

function($a){return!array_diff(array_count_values($a),[2]);}

Try it online!

PHP has great built-ins for this, though at 20 chars, array_count_values() is not a very golfy one.

640KB

Posted 2019-07-08T08:55:20.303

Reputation: 7 149

PHP always has great built-ins, with long names, sigh! – Night2 – 2019-08-06T11:06:18.877

3

Mathematica, 25 24 bytes

MatchQ[{{_,2}..}]@*Tally

Try it online!

The Tally function returns a list of the form {{element, count}, ...}, which is then matched against a pattern that checks whether all count are 2.

Doorknob

Posted 2019-07-08T08:55:20.303

Reputation: 68 138

3

Attache, 16 bytes

${All&x!{_~x=2}}

Try it online!

Explanation

${All&x!{_~x=2}}
${             }    lambda with input x
  All&x!{     }     over each element _ of x:
         _~x            check that the number of occurrences of _ in x
            =2          is 2

Alternatives

17 bytes: {All&_!`=&2@`~&_}

18 bytes: {All[`=&2@`~&_,_]}

23 bytes: Same@2&`'@Sum@Table[`=]

25 bytes: Same«2'Sum@Table[`=,_]»

25 bytes: Same<~2'Sum@Table[`=,_]~>

25 bytes: {Same[2'Sum@Table[`=,_]]}

35 bytes: {Commonest@_==Unique@_and _[0]~_=2}

Conor O'Brien

Posted 2019-07-08T08:55:20.303

Reputation: 36 228

3

K (oK), 9 bytes

Solution:

&/2=#:'.=

Try it online!

Explanation:

&/2=#:'.= / the solution
        = / group
       .  / value
    #:'   / count (length of) each
  2=      / equal to 2?
&/        / take minimum

streetster

Posted 2019-07-08T08:55:20.303

Reputation: 3 635

3

Julia 1.0, 32 bytes

l->sum(isone,l./l')/length(l)==2

Try it online!

Divides each element of the input array l by the transpose l' giving a matrix. Summing over this matrix while applying isone to each element gives twice the length of l if each element appears exactly twice.

TimD

Posted 2019-07-08T08:55:20.303

Reputation: 71

3

Julia, 30 characters 26 bytes

!a=all(x->2==sum(a.==x),a)

Thank you, H.PWiz for this trick!

Try it online!

user3263164

Posted 2019-07-08T08:55:20.303

Reputation: 381

1You can have !a=all(x->2==sum(a.==x),a) for 26 bytes. NB. that I recommend counting in bytes on this site – H.PWiz – 2019-08-06T16:06:37.857

Thank you very much! I didn't know you could (ab)use ! for anonymous functions – user3263164 – 2019-08-06T16:15:23.493

2

Octave / MATLAB, 22 21 bytes

@(x)any(sum(x==x')-2)

Anonymous function that inputs a numeric vector, and outputs 0 if the vector satisfies the condition or 1 otherwise.

Try it online! Or verify all test cases.

Explanation

@(x)                   % define anonymous function with input x
            x          % x
               x'      % x transposed and conjugated
             ==        % equality comparison, element-wise with broadcast. Gives a
                       % square matrix
        sum(     )     % sum of each column
                  -2   % subtract 2, element-wise
    any(            )  % true if and only if any value is not zero

Luis Mendo

Posted 2019-07-08T08:55:20.303

Reputation: 87 464

2

Elm 0.19, 66 bytes

n a=List.all(\x->List.foldl(\y c->if x==y then c+1 else c)0 a==2)a

Verify all test cases here.

For every item, iterate over the list and count how many items it is equal to. Return True if the count is exactly 2 for each item, False otherwise.

O.O.Balance

Posted 2019-07-08T08:55:20.303

Reputation: 1 499

2

Jelly, 5 bytes

ĠẈ=2Ạ

Try it online!

A monadic link that takes a list of integers and returns 1 if a Noah list and 0 if not.

Nick Kennedy

Posted 2019-07-08T08:55:20.303

Reputation: 11 829

2

MATL, 6 bytes

8#uqqa

Try it online!

0 for truthy, 1 for falsy. Ports Robin Ryder's answer.

MATL, 6 bytes

&=s2=A

Try it online!

1 for truthy, 0 for falsy. Ports Luis Mendo's answer.

Giuseppe

Posted 2019-07-08T08:55:20.303

Reputation: 21 077

2

Kotlin, 96 77 69 51 bytes

fun f(t:List<Int>)=t.count{t.count{i->it==i}!=2}==0

Try it online!

Quinn

Posted 2019-07-08T08:55:20.303

Reputation: 1 153

2

Ruby, 29 bytes

->a{a.all?{|e|a.count(e)==2}}

Try it online!

Value Ink

Posted 2019-07-08T08:55:20.303

Reputation: 10 608

2

Excel, 45 bytes

=SUM(IF(FREQUENCY(A:A,A:A)=2,1))=COUNT(A:A)/2

Assumes data in column A, with this entered in any cell other than one in column A. Returns TRUE if there are pairs and FALSE if they are not matching pairs

        FREQUENCY(A:A,A:A)                     Counts how many of each value there is
     IF(                  =2,1)                If this is 2, add value of 1 to array otherwise 0
=SUM(                          )               Sum the count in that array that have a exactly 2
                                 COUNT(A:A)/2  Count how many total values in column
                                =              If this is equal, return TRUE else FALSE

Tried removing the /2 and adding .5 for the summing, but this did not work.
Tried counting the frequencies that are <>2 and this did not return the right amount.

Keeta - reinstate Monica

Posted 2019-07-08T08:55:20.303

Reputation: 938

2

Powershell (5.1), 20 48* Bytes:

I setup my variables like this (which may not be correct):

 $a = (7,13,9,2,10,2,4,10,7,13,4,9)

I then add that variable to:

$a |group|%{$m=@{}}{$m[$_.Name]=($_.Count)-eq2}{$m}

This outputs the "Name" and "True" or "False" (could also use the animals names & it would work)

  • group - Groups the items
  • % - Abbreviation for For-Each
  • $m=@{} - Assigns the new variable
  • $_.Count-eq2 - Item count that equals 2
  • $y - List each item with True or False (if it equals 2)

Results are similar to this:

Output

*Note: This answer has been edited as I bungled things the first multiple times...

DBADon

Posted 2019-07-08T08:55:20.303

Reputation: 141

I think that screenshot is from a different challenge? :S Could you perhaps post a screenshot with some of the test cases for this challenge as verification? – Kevin Cruijssen – 2019-07-09T06:17:31.587

Standard rules requires that the code should be "programs or functions". For Powershell, this means that the code can be saved as a file with the .ps1 extension and executed as a script. Your code is a snippet, not "programs or functions". – mazzy – 2019-07-09T08:13:46.847

Sorry, I bungled this one. I reused my variables so it appeared my code was working great. I may have misunderstood the variables as well. I am updating my answer again now. – DBADon – 2019-07-10T16:58:29.197

I edited my post and it should work now. I think I can make it a bit smaller if I set it up differently and use the original $a variable & remove the need for the $m. I just don't have time to work it out right now... – DBADon – 2019-07-10T17:19:53.887

1

A few things: Your current code is 51 bytes, here's some examples on how to make your code take proper arguments, and lastly: your code stops one step short of finishing the problem. You have all the bools you need, still need to reduce it into one true/false return. Good first attempt though!

– Veskah – 2019-07-12T12:38:40.620

2

Bash, 26 bytes

Exit code is nonzero iff the list is of Noah.

sort|uniq -c|grep -v ' 2 '

Try it online!

jnfnt

Posted 2019-07-08T08:55:20.303

Reputation: 373

2

Factor, 53 bytes

: f ( s -- ? ) dup counts [ last ] map [ 2 = ] all? ;

Unfortunately dosn't work in TIO. Here's a screenshot of the Factor Listener (REPL):

Lists-of-Noah Factor Listener

Galen Ivanov

Posted 2019-07-08T08:55:20.303

Reputation: 13 815

2

Python 3, 37 bytes

lambda l:all(l.count(i)==2for i in l)

Try it online!

U10-Forward

Posted 2019-07-08T08:55:20.303

Reputation: 347

2

Jelly, 5 bytes

ċⱮ=2P

Try it online!

Not shorter than, but different than the existing jelly answer.

James

Posted 2019-07-08T08:55:20.303

Reputation: 54 537

2

Wolfram Language (Mathematica), 17 bytes

2==##&@@Counts@#&

Try it online!

Counts returns an association of <| (value)->(# occurences), ... |>. Then 2==##& checks if those occurence-counts are all equal to 2.

attinat

Posted 2019-07-08T08:55:20.303

Reputation: 3 495

2==##&@@ is brilliant! – Roman – 2019-08-06T12:20:11.723

1

Charcoal, 7 bytes

⬤θ⁼²№θι

Try it online! Link is to verbose version of code. Outputs - for a List of Noah. Explanation:

 θ      Input array
⬤       Do all elements satisfy the condition
    №   Count of
      ι Current element
     θ  In input array
  ⁼     Equals
   ²    Literal 2
        Implicitly output

Neil

Posted 2019-07-08T08:55:20.303

Reputation: 95 035

Whoa, that's one very charcoal circle. – Adám – 2019-07-08T10:08:39.500

1

Retina 0.8.2, 32 bytes

O`\d+
(\d+)(,\1)*\b
$#2
^1(,1)*$

Try it online! Link includes test cases. Explantion:

O`\d+

Sort the integers. (This is a string sort but it doesn't matter assuming no leading zeros.)

(\d+)(,\1)*\b
$#2

Count the number of duplicates of each integer.

^1(,1)*$

Each integer should have one other duplicate.

Neil

Posted 2019-07-08T08:55:20.303

Reputation: 95 035

1

Japt, 6 bytes

Outputs false for true and true for false.

ü mÊdÍ

Try it or run all test cases

ü mÊdÍ     :Implicit input of integer array
ü          :Group by value
  m        :Map
   Ê       :  Length
    d      :Any truthy (not 0)?
     Í     :  When subtracted from 2

Shaggy

Posted 2019-07-08T08:55:20.303

Reputation: 24 623

1

Pyth, 7 bytes

!n#2/LQ

Try it online!

!n#2/LQQ   Implicit: Q=eval(input())
           Trailing Q inferred
     L Q   For each element of Q...
    / Q    ... count its occurrences in Q
  #        Filter keep those elements...
 n 2       ... which are not equal to 2
!          NOT - maps [] to True, others to False
           Implicit print

Sok

Posted 2019-07-08T08:55:20.303

Reputation: 5 592

Another 7-byte solution is !smtt/Q – RK. – 2019-07-11T14:11:08.133

@RK Unfortunately.that one fails for input [1,2,2,2,3,4] :( – Sok – 2019-07-11T15:27:56.023

1

Wolfram Language (Mathematica), 38 bytes

Gather@#~Cases~{_,_}~Total~2==Total@#&

Try it online!

Comrade SparklePony

Posted 2019-07-08T08:55:20.303

Reputation: 5 784

1

Stax, 5 bytes

é♪Ccv

Run and debug it

Algorithm:

  1. Sort array.
  2. Get run-lengths.
  3. Remove all 2s from run-lengths.
  4. Result is empty?

recursive

Posted 2019-07-08T08:55:20.303

Reputation: 8 616

1

Red, 52 bytes

func[b][(extract sort b 2)= unique extract next b 2]

Try it online!

Galen Ivanov

Posted 2019-07-08T08:55:20.303

Reputation: 13 815

1

Python 3, 41 bytes

lambda x:set([x.count(i)for i in x])=={2}

Try it online!

Dat

Posted 2019-07-08T08:55:20.303

Reputation: 879

1

C, 84 83 bytes

c['   '],r,*p,*s,*e;f(){for(p=s;p<e;)c[*p++]++;while(s<e)r=c[*s++]-2?1:r;return r;}

Try it online!

f() returns 1 if the list is not a list of Noah, and 0 otherwise.

The variable s should point to the beginning of the array, and e should point to the end. Note that after f() is called, c must be reset to 0s before it can be called again. Also, this might not work on all computers, because I'm pretty sure multi-byte characters are implementation-defined, and it won't work if INT_MAX < 100000.

If I/O is very flexible, and outputting to a variable is enough, the return r; is unnecessary, and it can be reduced to 74 bytes.

De-golfed:

int counts[100001], return_value;

int f(int *start, int *end) {
        int *ptr;
        for (ptr = start; ptr < end; ptr++)
                counts[*ptr]++;
        for (ptr = start; ptr < end; ptr++) {
                if (counts[*ptr] != 2) {
                        return_value = 1;
                }
        }
        return return_value;
}

Thanks to @ceilingcat for -1 byte!

Leo Tenenbaum

Posted 2019-07-08T08:55:20.303

Reputation: 2 655

1

Functions should preferrably be reusable without massaging external values.

– gastropner – 2019-07-09T09:51:10.920

1

APL(NARS), 9 chars, 18 bytes

{⍵≡⍦,⍨∪⍵}

test:

  f←{⍵≡⍦,⍨∪⍵}
  f 7,13,9,2,10,2,4,10,7,13,4,9
1
  f 77,31,5,31,80,77,5,8,8
0
  f 2,4,6,4,4,4
0

RosLuP

Posted 2019-07-08T08:55:20.303

Reputation: 3 036

1

Dart, 66 bytes

f(n)=>n.map((m)=>n.where((o)=>o==m).length==2).reduce((p,e)=>p&e);

Try it online!

Elcan

Posted 2019-07-08T08:55:20.303

Reputation: 913

1

Vim, 45 bytes

:sor|%norm J
:g/^\v(.*) \1$/d
:g/./norm ggcG0

Try it online!

This will output nothing for a valid Noah list, and a 0 for an invalid Noah list.

James

Posted 2019-07-08T08:55:20.303

Reputation: 54 537

1

Brainfuck: 69

->+[>+<-[[-]+>->>[-]]+>[->++[-<<<+]->>]<,]>>>[>>[--[[-]>>-<[-]<]]>]>.

The bf interpreter/compiler needs to support 0 as EOF. It also need at least 300003 cells for be be used with number upto 100000. beef seems to match this.

The numbers are expected to come in as unary (whatever) terminated by ascii 1. It will output chr 0 on a valid set and chr 99 on an invalid set. If your terminal has UTF-8 you'll get some complaints or a replacement chars (the ?) as an indication.

The code uses bf memory as the first cell as an -1 flag that it seeks to after every number. Each number triggers it to jump 3 cells, since I have a 3 cell item and the whole BF memory is considered an array:

flag (-1) [ visited | flag | count ]* 

Thus if you supply 3 it will set count on the third index to 1 and every visited flags to 1 upto that.

I've tested like this:

#!/usr/bin/fish
set -l tests '[7,13,9,2,10,2,4,10,7,13,4,9]
[1,2,3,1,2,3]
[10,100,1000,1,100,10,1000,1]
[123,123]
[8,22,57189,492,22,57188,8,492,57188,57189,1,1]
[6,4,4,6,4,7,4,7]
[2,2,2,2,2,2]
[5,1,4,5,1,1,4]
[77,31,5,31,80,77,5,8,8]
[1,2,3,2,1]
[44,4,4]
[500,30,1]
[1,2,1,1]
[2,4,6,4,4,4]
[2,23,34,4]
[2,23,3,3,34,4]
'

for in in (echo $tests)
  echo -n $in :
  echo $in | perl -pe 's/(\d+)/"1" x $1/ge;s/[^\]\d,]//g;s/(?:]|,)/\x01/g;' | beef  moses.bf
  echo ''
end

And got the following output:

[7,13,9,2,10,2,4,10,7,13,4,9] :
[1,2,3,1,2,3] :
[10,100,1000,1,100,10,1000,1] :
[123,123] :
[8,22,57189,492,22,57188,8,492,57188,57189,1,1] :
[6,4,4,6,4,7,4,7] :[Invalid UTF-8] \xff
[2,2,2,2,2,2] :[Invalid UTF-8] \xff
[5,1,4,5,1,1,4] :[Invalid UTF-8] \xff
[77,31,5,31,80,77,5,8,8] :[Invalid UTF-8] \xff
[1,2,3,2,1] :[Invalid UTF-8] \xff
[44,4,4] :[Invalid UTF-8] \xff

Sylwester

Posted 2019-07-08T08:55:20.303

Reputation: 3 678

1

Kotlin, 46 45 bytes

fun f(l:IntArray)=l.all{l.count{i->it==i}==2}

Try it online!

Andrei-Cristian Rad

Posted 2019-07-08T08:55:20.303

Reputation: 11

Welcome to the site! – Laikoni – 2019-07-31T11:54:57.790

1

Swift 5.1, 63 bytes

let x={(a:[Int])in a.allSatisfy{v in a.filter{v==$0}.count==2}}

When the count(where:) function will be available, it'll become:

let x={(a:[Int])in a.allSatisfy{v in a.count{v==$0}==2}}

Try it online!

Tiziano Coroneo

Posted 2019-07-08T08:55:20.303

Reputation: 141

Welcome to the site! – Laikoni – 2019-07-31T11:56:22.307

1

jq, 30 characters

group_by(.)|map(length==2)|all

Sample run:

bash-5.0$ jq 'group_by(.)|map(length==2)|all' <<< '[7,13,9,2,10,2,4,10,7,13,4,9]'
true

Try it online!

Try all test cases online!

manatwork

Posted 2019-07-08T08:55:20.303

Reputation: 17 865

1

///, 358 299 bytes

/|/\/\///`/'\\|&/%`\%`\%T;`\%R;N`\%T;`\%|:/\\\\|;/`\`\|_/%%|%/`/|%<-::>:::|QT/%R'N%Q'T_<-;>%<-;;>;;_<`->%_L`S%L'S_-` *%-`{*[_-`{*%{-_!`{%{!_^`{*%^{-_[`*%*[_-`*%*-_!`*%*!_-`[%[-_!`[%[!_{`[%!_^`!%^-!_-`$%$_-`!!`$%$_-`!$&0_!`!!$&0_^`$&1_Q`T%Q'T%R'N|RN/QT|<-:>/<-::>::|<\->/|!*/!-|-*/--|LS/^!DATA GOES HERE$|Q\T/QT/RN

Try it online!

Try it online! (legible-ish version)

I don't know if this is the first Code Golf answer which uses an actual computational loop in slashes, but I'm very proud of it regardless. The loop construction I use is due to Ørjan Johansen, and is elaborated on on the wiki (although not in very high detail, and he uses | instead of '). There is a whole lot of escaping involved.

Input is in the form of a string which replaces DATA GOES HERE in the source code. The string should be a -delimited list of unary numbers with * representing one. Output is 1 if the list is a list of Noah, 0 if it is not.

Explanation

  • The program revolves around the manipulation of the input string, which is prefixed by ^! and suffixed by $. First, the following two substitutions are made: /!*/!-/ and /-*/--/, which turn the first number of the input into dashes. It will be the number line for recording the whole list.
  • The rest of the program is inside a loop (not presented in the same order as in the program). First, it organizes the data
/- */-\{*[/ /[*/*[/    turn the next number into a "rocket"
                       eg `^!--- **` => `^!---{**[`
/-{*/{-/               the front of the rocket moves forward by "using up fuel"
/!{/{!/                moving forward through a `!` does not cost any fuel
/-*/*-/ /!*/*!/ /-[/[-/ /![/[!/
                       the rest of the rocket follows the head
/^{*/^{-/              the rocket extends the number line if it runs out of room
/{[/!/                 once the rocket runs out of fuel, it becomes a `!`
  • Since a rocket travels a number of -s equal to the number it came from, the result is a backwards number line where every member of the original list is marked with !s, eg ^!*** ** *** *****$ => ^!--!!-!--$
  • When the last number turns into a rocket, the $ begins inspecting the number line:
/^!/^-!/                 needed for some of the following to work
/-$/$/ /-!!$/$/          the inspector finds things satisfactory so far
/-!$/N\O/ /!!!$/N\O/     the inspector has rejected this input
/^$/Y\S/                 the inspector has accepted this input
  • The loop works by replacing a "variable" RN with a copy of the relevant code. The simplest way to stop the loop and output the result is to conditionally replace RN with the result so that the loop can't continue. We do this by replacing YS and NO with a replacement that replaces RN with the relevant value: /YS/\/\/T\\\/R\\N\/T\\\/1/ /NO/\/\/T\\\/R\\N\/T\\\/0/. (It is //f/r instead of /f/r/ because the YS and NO values already exist inside a replacement, so it becomes works like, eg, /LS/YS/ => /LS///RN/1/

Notes

Variables are two letters because you have to be able to escape them by putting a \ in the middle (/V\R/val/ is equivalent to /VR/val/), otherwise they'll replace themselves in the copy that's used for looping.

At the beginning of the program are several "golfing substitutions" which serve no purpose other than to make the program shorter and even less legible.

59 bytes saved by using direct replacement instead of YS and NO, and doing 2 more golfing substitutions (& for the replacement-replacement which is nearly the same for accepting and rejecting, and ` for '\)

stellatedHexahedron

Posted 2019-07-08T08:55:20.303

Reputation: 871

1

PHP, 58 bytes

for(;$n=$argv[++$i];$a[$n]++);echo min($a)==2&&max($a)==2;

Each number in the list is passed as an argument.

Outputs 1 for truthy and nothing for falsey.

Try it online!

Tests

Night2

Posted 2019-07-08T08:55:20.303

Reputation: 5 484