Einführung und Kredit
Wir alle kennen und lieben unsere großartigen Regeln, um zu testen, ob eine Zahl durch 11 oder 3 teilbar ist. Dies ist nur eine clevere Summe über den Ziffern der Zahl. Diese Herausforderung bringt dies auf ein neues Niveau, indem Sie die Summe der Ziffern berechnen und dann prüfen müssen, ob das Ergebnis ein perfektes ganzzahliges Quadrat ist, wobei keine der beiden Operationen normalerweise sehr kurz ausgeführt werden kann. Da diese Eigenschaft auch bei der Betrachtung einer Zahl sehr schwer zu erkennen ist, möchten wir, dass dies für ganze Zahlenlisten durchgeführt wird, um menschliche Arbeit zu sparen. Das ist jetzt also Ihre Herausforderung!
Dies war eine Aufgabe in meinem Kurs für funktionale Programmierung an der Universität. Diese Aufgabe ist jetzt abgeschlossen und wurde im Unterricht besprochen. Ich habe die Erlaubnis meines Professors, sie hier zu posten (ich habe ausdrücklich darum gebeten).
Spezifikation
Eingang
Ihre Eingabe ist eine Liste nicht negativer Ganzzahlen in einem beliebigen Standard-E / A-Format.
Sie können das Listenformat so wählen, wie es Ihre Sprache benötigt
Ausgabe
Die Ausgabe ist eine Liste von Ganzzahlen in jedem Standard-E / A-Format.
Was ist zu tun?
Filtern Sie jede Ganzzahl aus der Eingabeliste heraus, für die die Summe der Ziffern kein Quadrat (einer Ganzzahl) ist.
Die Reihenfolge der Elemente darf nicht geändert werden, z. B. wenn Sie erhalten [1,5,9]
, können Sie nicht zurückkehren[9,1]
Mögliche Eckfälle
0 ist eine nicht negative Ganzzahl und somit eine gültige Eingabe, und 0 ist auch eine gültige Ganzzahlwurzel, z. B. zählt 0 als ganzzahliges Quadrat.
Die leere Liste ist auch eine gültige Eingabe und Ausgabe.
Wer gewinnt?
Das ist Code-Golf, also gewinnt die kürzeste Antwort in Bytes!
Es gelten selbstverständlich Standardregeln.
Testfälle
[1,4,9,16,25,1111] -> [1,4,9,1111]
[1431,2,0,22,999999999] -> [1431,0,22,999999999]
[22228,4,113125,22345] -> [22228,4,22345]
[] -> []
[421337,99,123456789,1133557799] -> []
Schritt-für-Schritt-Beispiel
Example input: [1337,4444]
Handling first number:
Sum of the digits of 1337: 1+3+3+7=14
14 is not an integer square, thus will be dropped!
Handling second number:
Sum of the digits of 4444: 4+4+4+4=16
16 is an integer square because 4*4=16, can get into the output list!
Example output: [4444]
Antworten:
Pyke, 6 bytes
Try it here!
quelle
Mathematica,
3936 bytesAn anonymous function:
LLlAMnYP saved a byte. Thank you!
Martin Ender saved three more by replacing
IntegerQ
withAtomQ
. Clever! (The result of√
will be exact, so it returns a compound expression likeSqrt[5]
if its argument isn’t a square.)quelle
...Digits@#&
instead of...Digits[#]&
Jelly,
87 bytes1 byte thanks to @Sp3000.
Test suite.
Explanation
quelle
Brachylog v2, 8 bytes
Try it online!
Explanation
The
&
means that the elements output are the same as those in the input list, but theℤ
will error out if the block's input isn't a square number, so we get the input list with elements with non-square digit sums discarded.Note that there might at first seem to be a floating point inaccuracy issue here (some very large non-square integers have integer square roots due to rounding). However, Brachylog supports bignum arithmetic, and actually has this behaviour factored into its implementation of
√
: a number which is a perfect square will have its square root reported as an integer, whereas a number which is not a perfect square (but close enough that its square root is integral) will have its square root reported as a float with an integral value. Conveniently,ℤ
only permits the former sort of return value, giving an assertion failure for the latter.quelle
Pyth, 10 bytes
Test suite.
Explanation
quelle
CJam, 14 bytes
Thanks to @FryAmTheEggman for saving one byte!
Try it online!
This is an unnamed block that expects the input list on the stack and leaves the filtered list on it.
Explanation
quelle
Haskell -
706059 bytesUsage:
Quite straightforward; computes the sum of digits and checks if floor(sqrt(y))^2 == y
Edit: Stole the idea of checking list of squares from C. Quilley
quelle
f=
is required for this answer.05AB1E,
1910 bytesExplanation
Try it online
Edit: Saved 9 bytes thanks to @Adnan
quelle
vySO
and check immediately if it's square or not. I got this to 5:tDï->
. There also is a special builtin that printsy
when equal to1
, which is (—
). So, that would bevySOtDï->—
.R,
5755 bytesUse
Filter
on the vector. Assumes 32 bit integers so 10 digits max.Corner cases: returns
NULL
for the empty vector andnumeric(0)
for a vector with no valid numbers. These both have length zero so should be acceptable.-2 thanks to @Giuseppe
Try it online!
quelle
PowerShell,
6454 bytesTry it online!
-10 bytes thanks to mazzy
Takes input as command-line arguments (see examples below), which gets processed in PowerShell into the array
$args
. We pipe that to?
an alias forWhere-Object
(functions similar tofilter
) in order to select our output. Our selection is based on the .NET call[math]::Sqrt()
of the digit-sum of the number is an integer with!(...%1)
. Integers will result in 0, which whennot
ed becomesTrue
while non-integer roots becomeFalse
.As mentioned elsewhere "returning" an empty array is meaningless, as it's converted to
$null
as soon as it leaves scope, so the output for an empty input is nothing.Examples
quelle
$n%1
checks if int only$args|?{!([math]::Sqrt(([char[]]"$_"-join'+'|iex))%1)}
Python 2, 76 bytes
Try it here!
Some abuse of eval to check for a square number, rest is pretty unspectacular.
The eval statement evaluates to
sum(map(int,
n))**.5==int(sum(map(int,
n))**.5)
quelle
Oracle SQL 11.2, 213 bytes
Un-golfed
quelle
Brachylog, 26 bytes
Example:
Explanation
This is a situation where something works a bit too well... the
~^[X:2]
part is true for both positive and negativeX
, so to avoid duplicates I have to specify thatX > 0
.The
;.0
part is here due to a bug (enumerate doesn't work on the integer 0).Main predicate
Predicate 1
quelle
Python 2, 53 bytes
Test it on Ideone.
quelle
f([1111111111111111])
, it looks likerepr(n)
contains an'L'
andint('L')
throws aValueError
. I feel like you needstr(n)
here?J,
3327 bytes6 bytes thanks to @miles.
In online interpreters,
inv
is not instored. Change that to^:_1
instead.Usage
Where
>>
is STDIN and<<
is STDOUT.Slightly ungolfed
Previous 33-byte version
Usage
Where
>>
is STDIN and<<
is STDOUT.Slightly ungolfed
quelle
f&.g
to applyg
, thenf
, and then the inverse ofg
to shorten*:@<.@%:
to<.&.%:
saving 2 bytes. You can rearrange it and use only floor to get#~[:(=<.)@%:+/"1@(10&#.inv)
for 27 bytes whereinv
is^:_1
, and is already defined.Javascript 66 bytes
Thanks for SergioFC for saving 7 bytes
quelle
c+d
instead ofc-+-d
? In addition you can usen%1==0
to test if the result is an int, so maybe you can save some bytes usingb=>!(Math.sqrt((b+"").split``.reduce((c,d)=>c-+-d))%1)
to filterPerl 5, 42 bytes
41, plus 1 for
-pe
instead of-e
Explanation:
-p
gets each input integer on a new line and assigns$_
to that string.my$s
initializes the variable$s
to nothing, anew for each input integer.map$s+=$_,/./g
grabs each numeric character and numerically adds it to$s
. (The newline becomes 0 when numified.)sqrt$s==~~sqrt$s
tests whether$s
has a nonintegral square root, and$_ x=
makes$_
into itself or the empty string depending on that test.-p
prints$_
Thanks to Brad Gilbert b2gills for saving three bytes.
Also 41 plus 1:
s/./$s+=$&/ger
adds each numeric character to$s
(and the newline is 0 as above)quelle
JavaScript (Node.js), 48 bytes
Try it online!
Explanation
quelle
MATL,
161413 bytesTry it Online!
Explanation
quelle
Julia - 38 bytes
It's pretty easy to see what this does.
digits
converts a number into a list of its digits,sum
thus calculates the digit-sum,√
will then produce a whole number if the number is a square, otherwise there will be a fractional part.%1
will return only the fractional part, and if it's zero (==0
),filter
will keep it on the list, otherwise it gets filtered out.Used as
![22228,4,113125,22345]
quelle
Jolf, 8 bytes
Try it here!
Explanation
quelle
MATLAB,
524342 bytesCreates an anonymous function named
ans
that can be called with an array as input:ans([22228,4,113125,22345])
.Online Demo. The online demo is in Octave which doesn't work for the empty input, but MATLAB does.
Explanation
We convert each element in the input array to base 10 which will yield a 2D character array where each row contains the digits of a number in the array. To convert these characters to numbers, we subtract 48 (ASCII for
'0'
). We then sum across the rows, take the square root, and determine whether each value is a perfect square~mod 1
. We then use this boolean to filter the input array.quelle
Clojure, 110 bytes
Calculates the sum of number digits and then filters out those for which there doesn't exist a number which squared is equal to the sum.
You can see the result here – https://ideone.com/ciKOje
quelle
Perl 6,
3835 bytesTest:
quelle
C,
143141 bytesUngolfed try online
quelle
Retina, 69
Because testing for perfect squares in retina. This can be modified for generalised integer square root calculation.
Input is a newline-separated list.
Try it online.
a
a
to unary expressed asb
s, separated with spacesquelle
%
-configuration,\G
and forward references. Feel free to take it: retina.tryitonline.net/… :)Python, 50 bytes
If n is input list of numbers
quelle
Ruby, 39 bytes
Try it online!
quelle
K (oK),
191713 bytesSolution:
Try it online!
Explanation:
Notes:
quelle
func#list
)?MathGolf,
54 bytesTry it online!
Explanation:
MathGolf is still in development,
so I assume implicit input is coming soon to shave off that first byte.Yay!quelle