Ausdauer essen
Intro
Finden Sie das Ergebnis des Kannibalismus.
Warum hatte 6 Angst vor 7? Werden 7 89.
Ihr Programm muss das Ergebnis der 8wiederholten Anwendung der Operation (unten definiert) auf eine Zahl finden.
Verwandte , Sandbox
Herausforderung
Ihre Eingabe ist eine einzelne positive ganze Zahl, n.
Sie müssen jedes 8in der Ganzzahl finden und es durch +oder -basierend auf den folgenden Bedingungen ersetzen .
- Entfernen Sie alle
8s am Anfang oder Ende der Zeichenfolge. - Wenn es mehrere
8s gibt, reduzieren Sie sie zu einem einzigen8. - \.$a\$und \$b\$sind die Brocken links und rechts von
8. Da8es sich um einen Operator handelt, werden die Zahlen durch begrenzt8. - If \$ a ≥ b,\$
8wird+. - sonst wird es
-.
Bewerten Sie dann den Ausdruck von links nach rechts und nehmen Sie den absoluten Wert.
Wenn das Ergebnis 8s enthält, wiederholen Sie die obigen Schritte erneut, bis keine mehr vorhanden sind.
Zum Beispiel 12384568789wird:
123 456 7 9
123 < 456: 123 - 456 7 9
456 ≥ 7 : 123 - 456 + 7 9
7 < 9 : 123 - 456 + 7 - 9 = -335
= abs(-335)
= 335
Daher ist 335 die endgültige Antwort.
Beispiel für Ein- und Ausgabe
789 → 2
180 → 1
42312348 → 4231234
2389687 → 66
12384568789 → 335
13749547874394873104972349 → 7309154
808 → 0
7800482 → 13
14458883442 → 1997
88888 → indeterminate
388182 → 2
08182 → 3
Hier sind die Testfälle als Array:
[789,180,42312348,2389687,12384568789,13749547874394873104972349,808,7800482,14458883442,88888]
Bewertungskriterien
Das ist Code-Golf . Die kürzeste Antwort in jeder Sprache gewinnt.
Antworten
05AB1E , 18 14 Bytes
Δ8¡þDü@1š·<*OÄ
Probieren Sie es online aus oder überprüfen Sie alle Testfälle .
Erläuterung:
Δ # Loop until it no longer changes:
8¡ # Split the integer on 8s
# (which will use the implicit input-integer in the first iteration)
þ # Remove all empty strings by only leaving digits
D # Duplicate this list
ü # For each overlapping pair [a,b]:
@ # Check if a>=b (1 if truthy; 0 if falsey)
1š # Prepend a 1 to this list
· # Double each value
< # Decrease each by 1 (0 has become -1; 1 is still 1)
* # Multiply the values at the same positions in the two lists
O # Sum the list
Ä # And take the absolute value of this sum
# (after which the result is output implicitly)
Gelee , 20 18 Bytes
IŻṠo-×
ṣ8LƇḌÇSAµÐL
Probieren Sie es online aus!
Ich habe 5 oder 6 andere Ansätze durchlaufen, bevor sich herausstellte, dass eval der einzige war, den ich zur Arbeit bringen konnte ... und dann habe ich bei meinem zweiten Ansatz einen anderen Dreh versucht und er ist 2 Bytes kürzer.
Alte Version: ṣ8LƇḌ<Ɲị⁾_+ż@ƲFVAµÐL
IŻṠo-× Monadic helper link:
Ṡ signs of
I deltas
Ż with prepended 0,
o- replace all 0s with -1s,
× pairwise multiply with argument.
ṣ8LƇḌÇSAµÐL Main link:
ṣ8 split (implicitly converted digit list) on 8s,
LƇ remove empty slices,
Ḍ convert digit lists from decimal,
Ç apply helper link,
S sum,
A abs.
µÐL Loop that whole thing until it doesn't change.
JavaScript (ES6), 76 Byte
f=n=>n.replace(p=/[^8]+/g,x=>t-=p<(p=+x)?x:-x,t=0)&&n-(t=t<0?-t:t)?f(t+''):t
Probieren Sie es online aus!
Kommentiert
f = n => // f is a recursive function taking n as a string
n.replace( // we look for ...
p = /[^8]+/g, // ... all groups of consecutive non-eight digits
x => // for each group x:
t -= // update t:
p < (p = +x) ? // if the previous value is less than x:
x // subtract x from t
: // else:
-x, // add x to t
t = 0 // start with t = 0
) && // end of replace()
n - ( // if n is not equal to t,
t = t < 0 ? -t : t // where t is first updated to its absolute value:
) ? //
f(t + '') // do a recursive call with t (coerced back to a string)
: // else:
t // success: return t
Schale , 27 26 25 Bytes
Bearbeiten: -1 Byte durch Verwendung des SKombinators zum Recyceln von Funktionsargumenten und Verschieben der Hilfsfunktion in die Zeile und dann -1 weitere Byte durch ein wenig Neuanordnung, um den oKombinator anstelle von verwenden zu können()
ω(aΣSz*o:1Ẋȯ`^_1¬<mdfIx8d
Probieren Sie es online aus!
Ein etwas anderer Ansatz zur Antwort von Unrelated String's Husk , ebenfalls 27 Bytes .
Ich hatte mich ein wenig zurückgehalten, um jedem neuen Husker eine saubere Tafel zu geben, von der aus er diese Herausforderung ausprobieren konnte ... aber jetzt ist die Husketition offen ...
Wie? * *
mdfIx8d # helper function: splits input on 8s
d # get digits of input
x8 # split on 8
f # remove elements that are falsy for
I # the identity function (so, remove empty elements)
m # map over each element of the list
d # combining digits as decimal number
ωλaΣz*₁¹m`^_1ΘẊo¬<₁ # main program
ω # repeatedly apply function until results are constant
λ # lambda function taking one argument:
a # get the absolute value of
Σ # the sum of all elements of
z* # element-wise multiplication of
₁¹ # (1) helper function applied to input
# (so: the input split on 8s)
m # (2) map this function to all elements of
₁ # helper function applied to input
Θ # (with 0 prepended at the start)
`^_1 # minus one to the power of
Ẋ # the results for each pair of elements
o # combine 2 functions
¬ # NOT
< # second is greater than first
R , 89 122 Bytes
Bearbeiten: +33 Bytes zum Konvertieren in eine rekursive Funktion, als mir klar wurde, dass der 8Vorgang an seiner eigenen Ausgabe wiederholt werden sollte, bis keine 8s mehr vorhanden sind . Doh!
f=function(s)`if`(grepl(8,a<-abs(sum(c(1,-sign(diff(n<-sapply((n=el(strsplit(s,8)))[n>-1],as.double))))*n))),f(c(a,'')),a)
Probieren Sie es online aus!
Akzeptiert das Argument nals Zeichenfolge. Fehler für ns, die keine Nicht-8-Ziffern / Zeichen enthalten.
Python 3 , 158 148 145 138 Bytes
x=input()
while'8'in x:
y=[int(f)for f in x.split('8')if f];x=str(sum([-1,1][y[i-1]<y[i]]*y[i]for i in range(len(y))))
print(abs(int(x)))
Probieren Sie es online aus!
-10 Bytes dank @ pavi2410 und weil ich kein Idiot bin und versehentlich einen zusätzlichen Platz vom Golfvorschlag gelassen habe
und noch ein -3 dank @ pavi2410
und noch ein -7 danke an @ pavi2410
C (gcc) , 149 \$\cdots\$ 139 137 Bytes
2 Bytes dank Ceilingcat gespart !!!
8 Bytes dank AZTECCO gespart !!!
R;t=10;m;s;p;c;f(n){R=n;for(s=p=0;n;){for(m=1,c=0;n&&n%t-8;n/=t,m*=t)c+=n%t*m;s+=c>p?p:-p;for(p=c;n%t==8;)n/=t;}p=abs(s+c);R=p-R?f(p):p;}
Probieren Sie es online aus!
Erklärung (vor einigen Golfspielen)
t=10; // golf by storing 10 in t
g(n){ // helper function takes int n
for( ;n;){ // loops until n is zero
s=p=0 // init sum s and previous p to 0
for( // inner loop calculates next rh value
m=1, // init multiplier m to 1
c=0; // and current c to 0
n&& // loop until n is 0
n%t-8; // or most rh digit is 8
n/=t, // knock most rh digit off n
m*=t) // and bump m by 10 each loop
c+=n%t*m; // add next digit to current
// building up number after
// most right-hand 8
s+=c>p?p:-p; // after that's done update sum s
for( // loop to strip off all rh 8's
p=c; // also make previous = current
n%t==8;) // loop until most rh digit isn't an 8
n/=t; // knock most rh 8 off n
} //
p=abs(s+c); // return abs value of sum with
// positive most lh value
} //
f(n){ // recursive main function
x=g(n); // calc first iteration
x=x-g(x)? // is it different to next iteration?
f(x): // if so iterate
x; // else return value
} //
Perl 5 -p , 59 Bytes
y/8/ /;s/\d+/$&<$'?"$&-":"$&+"/ge;$_=abs eval$_.0;/8/&&redo
Probieren Sie es online aus!
J , 53 Bytes
|@('8'+/@(*_1x^0,2</\])@(,(*@#;._1#".;._1)~[=,)":)^:_
Probieren Sie es online aus!
Wie es funktioniert
f^:_: bis sich das Ergebnis nicht ändert, f.'8'…(,g[=,)":: Konvertieren Sie die Eingabe in eine Zeichenfolge, stellen Sie,das Zeichen voran8und führen Siegdies als linkes Argument und eine Bitmaske von8Zeichen als rechtes Argument aus.(…".;._1)~: Teilen Sie die Zeichenfolge in Gruppen aufu;._1, die mit 1 in der Bitmaske beginnen, und konvertieren Sie sie zurück in Zahlen".(ohne die8).*@#;._1#: weil wir leere Gruppen haben könnten (888), nimm#nur diejenigen, deren#Längensignum 1*ist. (Es könnte einen schöneren Ansatz geben.)2</\]: Vergleichen Sie<jede Gruppe mit der folgenden, was zu einer Bitmaske führt.*_1x^0,: 0 auf die Bitmaske und berechnet prependx*(-1)^yfür jede Gruppexmitywobei das Ergebnis des Vergleichs. Also bekommen wir3 1 2 -> 3 1 _2.|@…+/: Summiere+/das Ergebnis und nimm den absoluten Wert|.
Scala , 94 90 Bytes
i=>"[^8]+".r.findAllIn(""+i).map(_.toInt).scanRight(0){(a,b)=>if(a<b.abs)a else-a}.sum.abs
Probieren Sie es online aus!
-4 Bytes, wenn die verfluchte splitMethode von Java nicht verwendet wird.
i=> //The input
"[^8]+".r //Regex for operands
.findAllIn(""+i) //Get all separate numbers in the input
.map(_.toInt) //Turn them into integers
.scanRight(0){(a,b)=> //Starting at the right,
if(a<b.abs)a else-a} //Replace a with -a if a >= b.abs (this is different from the challenge, but it works because we call abs again later)
.sum //Sum them up
.abs //Take the absolute value
Schale , 27 Bytes
ω(aΣSz*(Ẋȯ`^_1±>Ṡ:←)mdfIx8d
Probieren Sie es online aus!
Dies ist nicht ganz meine erste Husk-Antwort, aber es ist eine ziemlich ungeschickte direkte Übersetzung einer meiner versuchten Jelly-Antworten, sodass sie zumindest als nützlicher Ausgangspunkt für jemanden dienen kann, der einspringt und das Kopfgeld verdient.
ω( Iterate until periodic:
a absolute value of
Σ sum of
z* zipwith multiplication on:
d decimal digits
x8 split on 8s
fI with empty slices removed
md and converted back from decimal,
S and the result of that
( Ṡ:←) with its first element duplicated
Ẋ and with neighboring pairs mapped to
`^_1 -1 to the power of
ȯ ±> if the first is less than the second.
Bash , 177 Bytes
A=($(sed s/8/\ /g<<<$1));B=;while [ ${#A[@]} -ge 2 ];do [ ${A[0]} -ge ${A[1]} ]&&C=+||C=-;B=$B${A[0]}$C;A=(${A[@]:1});done;R=$(bc<<<$B$A|tr -d -);grep -cq 8 <<<$R&&f $R||echo $R
Es muss als Funktion foder in einer Datei fim aktuellen Arbeitsverzeichnis gespeichert werden .
Probieren Sie es online aus!
PHP, 290 Bytes
(Ich denke, du solltest nicht in PHP Golf spielen :))
<?php $n=$_SERVER["argv"][1];while(false!==strpos($n,'8')){$n=abs(array_reduce(str_split(preg_replace('|8+|','8',trim($n,'8')).'8'),function($c,$i){if($i!=8){$c[1]*=10;$c[1]+=$i;}else{$c[2]+=$c[1]*((!isset($c[0])||$c[0]>=$c[1])?1:-1);$c[0]=$c[1];$c[1]=0;}return$c;},[null,0,0])[2]);}echo$n;
Probieren Sie es online aus
Ungolfed:
<?php
$n = $_SERVER["argv"][1]; $f=function($c, $i){
if($i!=8) { $c[1]*=10;
$c[1]+=$i;
} else {
$c[2] += $c[1] * ( (!isset($c[0]) || $c[0]>=$c[1])?1:-1); $c[0]=$c[1]; $c[1]=0;
}
return $c; }; while(false!==strpos($n,'8')) {
$n = trim($n, '8');
$n = preg_replace('|8+|', '8', $n);
$a = str_split($n.'8');
$n = abs(array_reduce($a, $f, [null, 0, 0])[2]); } echo $n;
Erläuterung:
Ich benutze array_reduce, um über jede Ziffer zu gehen, und verwende ein Array als Übertrag, um 3 Datenpunkte zu übertragen: die Variablen $a, $b und $sum, though they are unnamed as the elements of $c.
Wenn die aktuelle Ziffer eine Nicht-8 ist, füge ich sie meiner hinzu.$b", otherwise I first compare $b bis $a, add/subtract $b aus $sum, and move the content of $b bis $ a.
Rot , 142 Bytes
func[n][while[find to""n"8"][b: to[]load form split to""n"8"forall b[if b/2[b/1:
reduce[b/1 pick[- +]b/1 < b/2]]]n: absolute do form b]to 1 n]
Probieren Sie es online aus!
GolfScript , 32 Bytes
.,{8`%(~:x\{~.x\:x<2*(*-}/abs`}*
Probieren Sie es online aus!
Jedes Mal, wenn der Algorithmus ausgeführt wird, bleibt die Zahl entweder gleich oder sie wird mindestens eine Ziffer kürzer. Dies bedeutet, dass wir den Algorithmus einmal für jedes Byte ausführen können, anstatt zu testen, ob er eine 8 hat.
., # Get the number of bytes in the input
{ }* # Execute this block that many times
8`% # Split the string around the 8s and remove the empty strings
# This simultaneously executes the first 3 steps
(~ # Get the first number
:x # Store it in the variable x
\{~ }/ # For each number left in the array
.x # Copy it and push x
\:x # Store the current number in x
< # Compare the two numbers
2*( # 1 if previous<current and -1 if previous>=curret
*- # Multiply and subtract
abs` # Parse the absolute value to a string
Japt , 37 Bytes
@=q8 f;=äÈn ¨Y?Y:-Y}Ug)x a s ,Uø8}f U
Versuch es
- Nimmt die Eingabe als Zeichenfolge, kann sie leicht geändert werden, um die Eingabe als Zahl zu verwenden, funktioniert jedoch nicht mit großen Zahlen
'' '
@=q8 f;=äÈn ¨Y?Y:-Y}Ug)x a s ,Uø8}f U
@....}f - return first number which return false when passed through @...
=q8 f; - input splitted on 8 and empties removed
=äÈ...}Ug) - pass each consecutive values through È , but prepend first value before so that they are >=
n ¨Y?Y:-Y - 1st to number compared to 2nd: return 2nd (negated eventually)
x a s - reduce->abs->to string
The above is assigned to U while the funxtion returns..
Uø8 - contains 8? => repeat
Finally we return U
'' '
K (oK) , 60 43 38 Bytes
-22 Bytes dank Traws
{a|-a:+/{x*1-2*>':x}.:'(~^.)#"8"\$:x}/
Probieren Sie es online aus!
Retina 0,8,2 , 68 Bytes
{`8+
-
^-|-$ \d+ $*
(?=-(1*))(?<=\1)-
+
O`\D1*
\+
1>`-
(1+)-\1
1
Probieren Sie es online aus! Link enthält kleinere Testfälle (Retina muss unary subtrahieren, was für die größeren Fälle zu langsam ist). Erläuterung:
{`
Wiederholen, bis keine 8s mehr übrig sind.
8+
-
Konvertieren Sie jeden Lauf von 8s in a -.
^-|-$
Löschen Sie führende und nachfolgende -s.
\d+
$*
Konvertieren Sie die verbleibenden Zahlen in unär.
(?=-(1*))(?<=\1)-
+
Ersetzen Sie jedes -durch ein, es +sei denn, die folgende Zahl ist größer.
O`\D1*
Sortieren Sie die Zahlen, die am Anfang hinzugefügt werden sollen, und die Zahlen, die am Ende abgezogen werden sollen.
\+
Addieren Sie alle zu addierenden Zahlen.
1>`-
Addieren Sie alle zu subtrahierenden Zahlen.
(1+)-\1
Nehmen Sie den absoluten Wert der Differenz.
1
Konvertieren Sie es in eine Dezimalzahl.