# 递增数组

44

• 如果所有数组元素均相等，`1`则将a附加到数组末尾。例如：

``````[1] -> [1, 1]
[2] -> [2, 1]
[1, 1] -> [1, 1, 1]
[3, 3, 3, 3, 3] -> [3, 3, 3, 3, 3, 1]
``````
• 否则，增加数组中的第一个元素，即数组的最小值。例如：

``````[1, 2] -> [2, 2]
[2, 1] -> [2, 2]
[3, 1, 1] -> [3, 2, 1] -> [3, 2, 2] -> [3, 3, 2] -> [3, 3, 3]
[3, 4, 9, 3] -> [4, 4, 9, 3] -> [4, 4, 9, 4] -> [5, 4, 9, 4] -> [5, 5, 9, 4] -> ...
``````

（每个`->`代表一个增量，这是程序需要做的所有事情。）

0算作正整数

20
@Downgoat 0永远不会对PPCG有利。如果允许0，则该术语将为“非负”
ETHproductions 2016年

13

# 果冻，8 7 字节

``````‘;ṀỤḢṬ+
``````

### 这个怎么运作

``````‘;ṀỤḢṬ+  Main link. Argument: A

‘        Increment all elements of A.
Ṁ      Yield the maximum of A.
;       Concatenate both results. Note that the appended maximum will be the
minimum of the resulting array if and only if all elements of A are equal.
Ụ     Grade up; yield the indices of the resulting array, sorted by their
corresponding values in that array.
Ḣ    Head; extract the first index, which is the index of the first occurrence
of the minimum. For an array of equal elements, this will be the index
of the appended maximum.
Ṭ   Untruth; for index i, yield an array of i-1 zeroes, followed by a 1.
+  Add this array to A, incrementing the minimum or appending a 1.
``````

11

# Python 3，62 53 51 50字节

``def F(a):a+=1//len({*a})*[0];a[a.index(min(a))]+=1``

-9字节，感谢Lynn的发现，因为数组将是正整数，所以我可以在数组的末尾附加“ 0”并使之递增。

Yytsi '16

FlipTack

@TuukkaX我不确定。看起来还可以，但如果有的话，我将遵循有关就地修改数组的元共识。

1

mbomb007 '16

1
`a+=1//len({*a})*[0]`应该保存一个字节。

9

# JavaScript（ES6），61个字节

``a=>new Set(a).size>1?++a[a.indexOf(Math.min(...a))]:a.push(1)``

### 其他尝试

``````a=>a.some(x=>x-a[0])?++a[a.indexOf(Math.min(...a))]:a.push(1)
a=>a.some(x=>x-m,m=Math.min(...a))?++a[a.indexOf(m)]:a.push(1)
``````

``````a=>new Set(a).size>1?++a[a.indexOf(a.sort()[0])]:a.push(1)
// Instead we have to do:
a=>new Set(a).size>1?++a[a.indexOf(a.sort((x,y)=>x-y)[0])]:a.push(1)
``````

``f=(a,n=1,q=a.indexOf(n))=>~q?a.some(x=>x-n)?++a[q]:a.push(1):f(a,n+1)``

``a=>a.replace(m=/(\d+),(?!\1)/.test(a)?Math.min(...eval(a)):']',+m+1||",1]")``

Downgoat

@Downgoat我不确定如何使用它，因为它返回的是项目而不是索引
ETHproductions

-Downgoat

7

# Mathematica，70 57 55字节

``````±{p:x_ ..}:={p,1};±{x___,y_,z___}/;y≤x~Min~z:={x,y+1,z}
``````

JungHwan敏

`±`UTF-8中的@GregMartin （Mathematica默认使用UTF-8； try `\$CharacterEncoding`）是一个两个字节的字符（U + 00B1）。
JungHwan Min

@JHM UTF-8 不是 Windows上的默认字符编码。Mathematica可以在包含的单字节代码页中读取源文件`±`
Martin Ender

1
@ASimmons我在Windows上的全新Mathematica安装，`\$CharacterEncoding`设置`WindowsANSI`为CP1252（它与ISO 8859-1足够兼容，`±`并且`·`可以用于单个字节）。
Martin Ender

7

# 服从

``````#include<list>
#include<algorithm>
[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);};
``````

# 调用

``````std::list<int> s = {4, 4, 9, 4};

//invoke like this
auto i = [](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);};
i(s);

//or like that
[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);}(s);
``````

## 不打高尔夫球

``````#include <list>
#include <algorithm>
#include <iostream>
using namespace std;

void i(list<int>& l) {
auto e = l.end(), b = l.begin();

if (l.size() == count(b, e, l.front())) {
l.push_back(1);
} else {
++*min_element(b, e);
}
}

int main() {
list<int> s = {4, 4, 9, 4};

//invoke like this
i(s);

for (auto o:s)
std::cout << o << ' ';
std::cout << std::endl;
}
``````

EDIT2：我意识到我可以省略包含中的空格 `#include <list>`

EDIT3：通过更换挽救了两个多字节`l.begin()``begin(l)`

EDIT4：由于@Quentin，又节省了19（！）字节（请参阅他的评论）

EDIT5：Quentin减少了13个字节，谢谢！

EDIT6：正如TuukkaX指出的那样，未命名的lambda /函数就足够了，因此我删除`auto i=`了bytecount中的

5

Zgarb '16

1

Christian Sievers，2016年

1

1

Quentin

6

# 05AB1E，21 20 16字节

``````DÙgi0¸«}ÐWksgÝQ+
``````

``````                      # input = [3,2,1] used as example
D                     # duplicate input
Ùgi                  # if all elements are equal
0¸«}              # append 0
Ð             # triplicate list
# STACK: [3,2,1], [3,2,1], [3,2,1]
Wk           # index of minimum element
# STACK: [3,2,1], [3,2,1], 2
s          # swap top 2 elements of stack
# STACK: [3,2,1], 2, [3,2,1]
g         # length of list
# STACK: [3,2,1], 2, 3
Ý        # range [0 ... length]
# STACK: [3,2,1], 2, [0,1,2,3]
Q       # equal
# STACK: [3,2,1], [0,0,1,0]
# OUTPUT: [3,2,2]
``````

@Adnan：啊哈，好主意使用`ÝQ``k`。谢谢！
Emigna '16

5

## 从头开始，25 34块+ 7 6字节

``````lowval = 0
hival = 0
n = 1
for i in range(len(input)):
if(input[i] < input[lowval]):
lowval = i
if(input[i] > input[hival]):
hival = i
# No increment statement needed because python.
if(lowval == hival):
input.append(1)
else:
input[lowval] += 1
print(input)
``````

OldBunny2800 '16

Stewie Griffin

OldBunny2800 '16

1

OldBunny2800 '16

4

## J，25 22字节

``````(+~:*[=<./)@,0#~1=#@~.
``````

## 说明

``````(+~:*[=<./)@,0#~1=#@~.  Input is y.
#@    Is the length of
~.   deduplicated y
1=       equal to 1?
,0#~        Append that many 0s to y (one or none).
(         )@            Call the result z and apply this verb to it:
=                  take the bit array of equality
[                   between z
<./               and its minimum element,
*                    multiply that element-wise by
~:                     the bit array of first occurrences in z
+                       and add the result to z.
``````

3

# MATL，16字节

``````t&=?1h}t2#X<wQw(
``````

### 这个怎么运作

``````t         % Take input implicitly. Duplicate
&=        % Matrix of all pairwise equality comparisons
?         % If all comparisons were true
1h      %   Append 1 to the original copy ofthe array
}         % Else
t       %   Duplicate array
2#X<    %   Push minimum and index of its first occurrence
wQw     %   Swap, increment, swap (adds 1 to the minimum)
(       %   Assign the incremented minimum to that position
% End if implicitly. Display implicitly
``````

3

# Mathematica，56个字节

``````±{b:a_ ..}:={b,1};±a_:=a/.{p___,b:Min@a,q___}:>{p,b+1,q}
``````

``````±{b:a_ ..}:={b,1};±{p___,b_,q___}/;b<=p~Min~q:={p,b+1,q}
(* @GregMartin and I both independently came up with this above solution *)

±{b:a_ ..}:={b,1};±a:{p___,b_,q___}/;b==Min@a:={p,b+1,q}
``````

``````±{1, 1}
``````

`{1, 1, 1}`

``````±{3, 4, 5}
``````

`{4, 4, 5}`

3

``````f(a:b)|(x,y:z)<-span=<<(<).minimum\$a:b++[0|all(a==)b]=x++y+1‌​:z
``````

@Zgarb保存了8个字节，谢谢！

Zgarb

@Zgarb哇！
Christian Sievers，2016年

Angs，2016年

@Angs Monad是`(->)r`，应用于类型为`(->)r a = r->a`。然后从类型`return:: a->r->a``(>>=)::(r->a)->(a->r->b)->(r->b)`它们的实现是（我敢说吗？）很明显：`return=const``m>>=f = \r->f(m r)r`。后者正是需要什么来表达类似`span(predicate_depending_on l)l`，而提`l`一次。现在，仅在需要时才需要记住它。
Christian Sievers，2016年

Zgarb '16

3

# C＃，123 121 120 79 77个字节

``````using System.Linq;l=>{if(l.All(o=>o==l[0]))l.Add(0);l[l.IndexOf(l.Min())]++;}
``````

Cyoce

@Cyoce的确如此。我想到了同一件事，但是写了`Any`代替，`All`并且在想，那是行不通的：D谢谢！
Yytsi '16

2
C＃没有`++`吗？
Cyoce

TheLethalCoder

1
@Stefan Hmm。我还看到很多人`using`使用C＃删除了必需的，所以我不相信放弃它是合法的`using System.Linq`。除非我看到一条明确的声明说这是没有必要的，否则我会坚持下去。还是）感谢你的建议！:)
Yytsi'1

2

# Perl 6，46个字节

``{.[[==](\$_)??.elems!!.first(*==.min,:k)]++;\$_}``

（修改输入数组，并返回它）

## 展开：

``````{     # bare block lambda with implicit parameter ｢\$_｣

.[      # use the following as an index into the array

[==]( \$_ )    # reduce the array with ｢&infix:<==>｣

??              # if they are equal

.elems        # the value past the end ( ｢.end+1｣ would also work )

!!              # else

.first(       # find the first value
* == .min,  # where the element is equal to the minimum
:k          # return the key rather than the value
)

]++;              # increment it ( auto vivifies if it doesn't exist )

\$_                # return the modified array
}``````

2

# 果冻，9个字节

``````;1µ‘i¦E?Ṃ
``````

Alfie Goodacre

2

Mathematica，53个字节57个字节 59个字节

``````If[Equal@@#,#~Join~{1},x=#;x[[#~FirstPosition~Min@#]]++;x]&
``````

7

JungHwan Min

ngenisis

1

ngenisis

2

# R，72 66 65字节

``"if"(any((x=scan())-x[1]),"[<-"(x,u<-which.min(x),1+x[u]),c(x,1))``

-7个字节，感谢Giuseppe！

JayCe

@Giuseppe当然！
JayCe

1

# Ruby，46个字节

``````->a{a.uniq.size<2?a<<1:a[a.index(a.min)]+=1;a}
``````

6
`a.uniq[1]`如果有不同的价值观，那将是真实的。
histocrat

Cyoce '16

1

# 八度，69 67 64字节

``````function x=f(x)
[a,b]=min(x);if any(x-a),x(b)++;else x=[x,1];end
``````

``````[a,b]=min(x=input(''));if any(x-a),x(b)++;else x(end+1)=1;end;disp(x)
``````

1

## R，97个字节

``````if(all((a=scan())==a[1])){a=c(a,1)}else{while(!all(a==a[1])){a[which(a==min(a))][1]=min(a)+1}};a
``````

``````if(all((a=scan())==a[1]))
{
a=c(a,1)
}
else
{
while(!all(a==a[1]))
{
a[which(a==min(a))][1]=min(a)+1
}
a
``````

1

# TI基本（53字节）

``````If min(not(ΔList(Ans
Then
Ans->L1
cumSum(1 or Ans
min(Ans+ᴇ9(L1≠min(L1
L1(Ans)+1->L1(Ans
Else
augment(Ans,{1
End
``````

1

# Matlab的，83，77，71字节

``````function a=x(a)
if~nnz(a-a(1));a=[a,1];else[~,I]=min(a);a(I)=a(I)+1;end
``````

Stewie Griffin

`~nnz(a(a~=a(1)))`很简单`~nnz(a-a(1))`。另外，您不需要括号。`if ~nnz(a-a(1));a=[a,1];else[~,I]=min(a);a(I)=a(I)+1;end`。这应该短5个字节（注意：我尚未测试）。
Stewie Griffin

MattWH '16

@boboquack，该代码检查中的元素数`a`是否等于该向量中的最小值。向量`a = [3 4 6]`将导致`true`，向量`a = [4 4 6]`将导致`false`。我认为这在这里没有用...？
Stewie Griffin

1

Clojure，112100字节

``````(fn[a](if(apply = a)(conj a 1)(update a(apply min-key #(+(nth a %)(* % 1e-9))(range(count a)))inc)))
``````

``````(defn f[a](if(= 1(count(set a)))(conj a 1)(update a(apply min-key #(+(nth a %)(* % 1e-9))(range(count a)))inc)))
``````

hacky的134字节解决方案在更新向量之前先将其反向，然后再次反向返回：

``````(defn f[a](if(= 1(count(set a)))(conj a 1)(let[r #(vec(reverse %))a(r a)](r(update a(apply min-key #(nth a %)(range(count a)))inc)))))
``````

1

# Java 8、85 + 38 = 123字节

``import static java.util.Collections.*;``

``l->{if(min(l)==max(l))l.add(0);int i=0,n;while((n=l.get(i))>min(l))i++;l.set(i,n+1);}``

1

# MATLAB 66 53字节

``````if(range(a))[~,b]=min(a);a(b)=a(b)+1;else;a=[a 1];end
``````

``````a = [3 2]
``````

``````[3 2] -> [3 3] -> [3 3 1] -> [3 3 2] -> [3 3 3] -> [3 3 3 1] ...
``````

2

ბიმო

1

# SmileBASIC 3，101字节

``````DEF I A
M=MIN(A)IF M==MAX(A)THEN PUSH A,1RETURN
FOR C=0TO LEN(A)IF M==A[C]THEN INC A[C]BREAK
NEXT
END
``````

18Me21年

1

# SmileBASIC，77字节

``````DEF I A
IF MIN(A)==MAX(A)THEN PUSH A,0
WHILE A[I]>MAX(A)I=I+1WEND
INC A[I]END
``````

0

# Pyth，16个字节

``````?tl{QXxQhSQQ1+Q1
``````

``````?tl{QXxQhSQQ1+Q1  Program. Input: Q
?                 If:
l                The length
{Q              of Q deduplicated
t                 - 1
is non-zero:
X     Q1       Increment in Q at index:
xQ             Index in Q of
h            the first element
SQ          of Q sorted (minimum)
else:
+     Append
1   1
Q    to Q
Implicitly print
``````

0

`f z|and\$(==)<\$>z<*>z=z++[1]|1>0=z#minimum z where(x:z)#m|x==m=x+1:z;(x:z)#m|1>0=x:z#m;[]#_=[]`

``````incrementArray :: [Int] -> [Int]
incrementArray xs | and [x == y | x <- xs, y <- xs] = xs ++ [1]
| otherwise = g xs (minimum xs)
where g (x:xs) m | x == m = (x + 1):xs
g (x:xs) m | otherwise = x:g xs m
g [] _ = []``````

1

0

# 不可思议，44字节

``````@[dp1unq#0?:=#[:0(iO f\min#0)#0+1f]#0?++#0 1
``````

``````(@[dp1unq#0?:=#[:0(iO f\min#0)#0+1f]#0?++#0 1])[3 4 9 3]
``````

# 说明

``````@[
dp 1 unq #0
? set #[
get 0 (iO f\ min #0) #0
+ 1 f
] #0
? con #0 1
]
``````

0

## Kotlin，75个字节

``````fun a(s:MutableList<Int>){if(s.toSet().size<2)s+=0;s[s.indexOf(s.min())]++}
``````