We all often hear the idiom "walk through the array" to mean "map the function over the following array". However, I need it done (now!), so I want you to run through the array.
How do I run?
Imagine there's a wild pack of wolves behind you
Running through an array is like walking through one, except you can skip over elements. Yes, it's sometimes messy, but it (generally) works. "Which elements are skipped?", you may ask. Well, this is done at random. Let's walk through running through the array!
- Let
e
be the current element. - Let
random
generate a random float in[0,1)
. Ifrandom() < 0.5
, then you go the next element and then to step 1. (You may generate a number by other means, so long as their is an (ideally) equal chance of skipping and remaining. E.g., you can use choose an element from a two-member set and perform the action based on the result.) - Otherwise, you perform function
f
one
.
Objective
Given an array/list/string like either A
and a number K
, run through the array, adding K
to each member accessed. Output/return this array. A
will only contain non-negative integers, and K
will only ever be a non-negative integers. This is a code-golf, so the shortest program in bytes wins.
Test cases (examples)
K, A => possible K'
[1, 2, 3, 4], 0 => [1, 2, 3, 4]
[1, 2, 3, 4], 1 => [1, 3, 3, 5]
[0, 0, 0, 0], 2 => [2, 0, 0, 2]
23 Answers 23
Clojure, (削除) 41 (削除ここまで) 37 bytes
(fn[a k](map #(+(*(rand-int 2)k)%)a))
Knocked off a couple of bytes by multiplying by 0 or 1 and dropping the "if". Credit to most all of the other submitters!
-
\$\begingroup\$ An anonymouse function will suffice in this case, but nice answer; welcome to PPCG! \$\endgroup\$cat– cat2016年04月29日 22:41:18 +00:00Commented Apr 29, 2016 at 22:41
-
\$\begingroup\$ Many times
for
is shorter thanmap
, see my answer for reference :) Also it avoids having an inner anonymous function so instead of starting the code by(fn[a k]
you can use#(
. \$\endgroup\$NikoNyrh– NikoNyrh2016年12月26日 20:49:42 +00:00Commented Dec 26, 2016 at 20:49
Jelly, (削除) 9 (削除ここまで) (削除) 8 (削除ここまで) 7 bytes
From 8
to 7
thanks to @FryAmTheEggman.
+2X’¤¡€
Explanation
+2X’¤¡€
€ Map over each argument...
2X Choose a random number from {1,2}
’ Minus 1
¤ (grammar stuff)
¡ Repeat that number of times...
+ Add the second input (to the argument being mapped over).
-
\$\begingroup\$ How in the he-double-L do you successfully keyboard in this language?! \$\endgroup\$MonkeyZeus– MonkeyZeus2016年04月29日 19:39:24 +00:00Commented Apr 29, 2016 at 19:39
-
\$\begingroup\$ @MonkeyZeus Dennis said, it can be entered on Linux using a normal keyboard. \$\endgroup\$Bálint– Bálint2016年04月29日 19:52:59 +00:00Commented Apr 29, 2016 at 19:52
-
\$\begingroup\$ @Bálint The plot thickens, who is Dennis? lol \$\endgroup\$MonkeyZeus– MonkeyZeus2016年04月29日 20:11:18 +00:00Commented Apr 29, 2016 at 20:11
-
13\$\begingroup\$ @MonkeyZeus Ahem. \$\endgroup\$Dennis– Dennis2016年04月29日 20:29:00 +00:00Commented Apr 29, 2016 at 20:29
-
1\$\begingroup\$ @Dennis The prophecy has been fulfilled ┗( ⊙ .⊙ )┛ \$\endgroup\$MonkeyZeus– MonkeyZeus2016年04月29日 20:39:07 +00:00Commented Apr 29, 2016 at 20:39
Pyth, 7
m+*O2vz
Uses a random choice instead of floating point comparison, but should be indistinguishable.
Expansion:
m+*O2vz ## implicitly, a d and Q are added to the end of the program
m+*O2vzdQ ## Q = eval(input()), z= input()
m ## map over each element d of Q
+ d ## add to d
*O2vz ## the product of eval(z) and a random number chosen from [0, 1]
Using floating point:
m+*<.5O0vz
-
2\$\begingroup\$ floating point is floating point >:( \$\endgroup\$Leaky Nun– Leaky Nun2016年04月29日 17:00:42 +00:00Commented Apr 29, 2016 at 17:00
-
1\$\begingroup\$ @KennyLau the change is trivial, this was just golfier. I didn't think it was meant that it was required, just that the behaviour is the same. I'll add a version with fp and ask the OP. \$\endgroup\$FryAmTheEggman– FryAmTheEggman2016年04月29日 17:09:47 +00:00Commented Apr 29, 2016 at 17:09
-
\$\begingroup\$ @KennyLau what about languages without floating points? \$\endgroup\$Ven– Ven2016年04月29日 17:12:26 +00:00Commented Apr 29, 2016 at 17:12
-
\$\begingroup\$ @FryAmTheEggman Yes, it was just an example--equal probability is fine. \$\endgroup\$Conor O'Brien– Conor O'Brien2016年04月29日 18:40:06 +00:00Commented Apr 29, 2016 at 18:40
-
\$\begingroup\$ @KennyLau The OP has confirmed that floating point isn't necessary. \$\endgroup\$Alex A.– Alex A.2016年04月29日 18:41:42 +00:00Commented Apr 29, 2016 at 18:41
MATL, 11 bytes
tZy1$rEki*+
Uses floating point random numbers.
Explanation
t % implicit input (array). Duplicate
Zy % size (array specifying number of rows and columns)
1$r % random vector between 0 and 1 with that size
Ek % duplicate, round down: gives 0 or 1 with the same probability
i % input (number K to be added)
* % multiply: gives either 0 or K for each element
+ % add element-wise
-
1\$\begingroup\$ Typed from phone. Explanation later \$\endgroup\$Luis Mendo– Luis Mendo2016年04月29日 17:48:02 +00:00Commented Apr 29, 2016 at 17:48
-
\$\begingroup\$ @CatsAreFluffy :-) Done! \$\endgroup\$Luis Mendo– Luis Mendo2016年04月29日 22:33:03 +00:00Commented Apr 29, 2016 at 22:33
Japt, 6 bytes
®+V*Mq
Explanation
Implicit input of array U
and integer V
. Map (®
) over the array and, to each element, add V
multiplied by Mq
, which randomly generates either 0
or 1
. Implicit output of resulting array.
Ruby, 28 bytes
->a,k{a.map{|e|e+k*rand(2)}}
Julia, (削除) 33 (削除ここまで) (削除) 29 (削除ここまで) 27 bytes
x->k->x+rand(0:1,endof(x))k
This is an anonymous function that accepts an array with an inner anonymous function that accepts an integer and returns an array. To call it, assign it to a variable and call like f(x)(k)
.
We generate an array with the same length as the input array consisting of zeros and ones chosen at random with equal probability. We multiply this by the input integer and add that to the input array.
Saved 2 bytes thanks to Dennis!
Python 2, (削除) 60 (削除ここまで) 58 bytes
from random import*
lambda a,k:[e+choice([0,k])for e in a]
This program turned out really simple. There aren't many golfing tricks in there, apart from the the obvious "from module import*
", using a lambda instead of a regular function and the general lack of whitespace. Other than that it's actually quite idiomatic. If I was writing this for real I'd probably do it in a very similar way:
import random
def running_addition(seq, k):
return [e + random.choice([0, k]) for e in seq]
Or perhaps something more fancy:
import random
import operator
import functools
def run_through(seq, func):
def random_func(arg):
if random.randint(0, 1):
return func(arg)
return arg
return [random_func(e) for e in seq]
def running_addition(seq, k):
return run_through(seq, functools.partial(operator.add, k))
But that's enough showing off :)
This is the old, 60 byte version from when using a float for randomness was required:
from random import*
lambda a,k:[e+k*(random()<.5)for e in a]
For each element of the list, add k*(random()<.5)
. Python booleans evaluate to 0 and 1, so this adds 0 to any elements for which the condition isn't true.
Python's random.random()
returns floats in [0, 1)
, so I didn't have to worry about that.
-
1\$\begingroup\$ @FryAmTheEggman If the floating point requirement is dropped, the best I can figure out is to forget the multiplication trick entirely and do
e+choice([0,k])
\$\endgroup\$undergroundmonorail– undergroundmonorail2016年04月30日 21:57:10 +00:00Commented Apr 30, 2016 at 21:57 -
\$\begingroup\$ Ah quite right, nice way to avoid multiplying. That said the floating point requirement was removed so you can change your answer to that instead. \$\endgroup\$FryAmTheEggman– FryAmTheEggman2016年04月30日 22:07:04 +00:00Commented Apr 30, 2016 at 22:07
-
\$\begingroup\$ @FryAmTheEggman Oh haha, I didn't notice. I'll do that now, thanks :) \$\endgroup\$undergroundmonorail– undergroundmonorail2016年04月30日 23:07:12 +00:00Commented Apr 30, 2016 at 23:07
AWK, 56 bytes
x=NF{for(srand(systime());++i<x;)rand()>.5?$i+=$x:0}NF--
The random number generator in AWK has to be seeded or it will yield the same sequence of numbers every time the script is run. So that a big chunk of this code. The code expects the "array" to be a list of space separated numbers as commandline argument. The A
increment value is the last commandline argument.
x=NF{ }
Setting x
saves some characters, always evals to true
and the braces group the code run against the input line.
for(srand(systime()); )
The code block just one for
statement, which starts by seeding the random number generator.
++i<x;
The "should I iterate again" check iterates a counter to process all but the last commandline argument. The last one is the A
value from the challenge, so we need to ignore that.
rand()>.5?$i+=$x:0}NF--
The body of the loop increments the current commandline argument by the A
value using a ternary conditioned on the return value from the random number generator.
NF--
Once all the arguments have been incremented (or not), printing them is just a matter of decrementing the number of commandline arguments by one. That's always truthy, directs AWK to ignore the last one, and since there's no code block all the arguments are printed.
-
\$\begingroup\$ The argument of
srand()
is optional. You can removesystime()
, and still the random seed will follow the system date/clock. (According to gawk's and mawk's reference) \$\endgroup\$Pedro Maimere– Pedro Maimere2021年06月04日 07:22:08 +00:00Commented Jun 4, 2021 at 7:22
JavaScript (ES6), 38 bytes
solution=
a=>k=>a.map(n=>Math.random()<.5?n:n+k)
document.write("<pre>"+
[ [[1,2,3,4], 0], [[1,2,3,4], 1], [[0,0,0,0], 2], [[4,22,65,32,91,46,18], 42] ]
.map(c=>"["+c[0]+"],"+c[1]+": "+solution(c[0])(c[1])).join`\n`)
-
\$\begingroup\$ I want to participate in a challenge and...javascript is taken. Seriously, I'll learn unary. \$\endgroup\$Bálint– Bálint2016年04月29日 17:10:05 +00:00Commented Apr 29, 2016 at 17:10
-
\$\begingroup\$ @Bálint i'm pretty sure unary can't generate random floats \$\endgroup\$undergroundmonorail– undergroundmonorail2016年04月29日 17:34:49 +00:00Commented Apr 29, 2016 at 17:34
-
\$\begingroup\$ @undergroundmonorail I said it because no one uses it (for obvious reasons, like it can't be posted here because it becomes too long) \$\endgroup\$Bálint– Bálint2016年04月29日 17:45:41 +00:00Commented Apr 29, 2016 at 17:45
PowerShell v2+, 34 bytes
param($a,$k)$a|%{$_+$k*(random 2)}
Takes input $a
and $k
, the array and the int respectively. We then loop through the array and each loop iteration output the current element plus $k
times (random 2)
which will execute Get-Random -Maximum 2
(i.e., either a 0
or a 1
). These are all left on the pipeline and output as an array is implicit.
CJam, 10 bytes
{f{2mr*+}}
Expects the array and the number on top of the stack in that order and replaces them with the new array.
php 71 bytes
function f($s,$k){foreach($s as $v){$v+=rand(0,2)==0?k:0;echo $v.",";}}
k (12 bytes)
{x+y*(#x)?2}
e.g.
k){x+y*(#x)?2}[0 0 0 0;2]
2 2 2 0
More generally, where f
can be passed as an argument for 16 characters
{@[x;&(#x)?2;y]}
e.g.
k){@[x;&(#x)?2;y]}[0 0 0 0;2+]
0 0 2 0
-
\$\begingroup\$ Nice, including a general version! \$\endgroup\$Conor O'Brien– Conor O'Brien2016年04月30日 21:11:09 +00:00Commented Apr 30, 2016 at 21:11
Python 3 (削除) 152 (削除ここまで) (削除) 110 (削除ここまで) 98 bytes
This is my first code golf solution so I don't know any tricks. I tested this using a main function with test cases. The file size is only this function.
from random import*
def a(x,y):
p=0
for z in x:
if random()>.5:x[p]=z+y
p+=1
print(x)
Thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ for the advice on removing whitespace. Additional praise to @undergroundmonorail for advice that saved 12 bytes.
-
1\$\begingroup\$ I count 145 bytes. You can golf it by removing unneeded whitespace, such as between
import *
,a(x, y)
,x[ptr]=z+y
, etc. You can also replace the 4 spaces with a single space \$\endgroup\$Conor O'Brien– Conor O'Brien2016年04月29日 23:58:26 +00:00Commented Apr 29, 2016 at 23:58 -
\$\begingroup\$ You can put
x[ptr]=z+y
on the same line asif random()>0.5
to save 3 bytes of whitespace. In python 20.5
can be written as.5
to save a byte, I don't know if that's true in python 3 though. If you renameptr
top
you'll save 6 bytes in all. Also, are you on Windows? Windows stores newlines as two bytes, but since python doesn't care if the newline is one byte or two you can count it as 1, making your current solution only 103 bytes. By the way, welcome to PPCG :) \$\endgroup\$undergroundmonorail– undergroundmonorail2016年04月30日 17:40:55 +00:00Commented Apr 30, 2016 at 17:40
Clojure, 32 bytes
#(for[i %](+(*(rand-int 2)%2)i))
Thanks you David for rand-int
idea, definetely shorter than the if(>(rand)0.5)
approach. Here for
beats map
.
Factor, 29 bytes
[ '[ .5 [ _ + ] whenp ] map ]
'[ ... _ ... ]
Slot whatever is on top of the data stack (A) into the quotation at the_
.map
Apply a quotation to each member of a sequence (K), collecting the results into a sequence of the same length..5 [ _ + ] whenp
whenp
is a version ofwhen
that takes a probability instead of a boolean. In other words, there is a 50% chance thatwhenp
's quotation will be called.
Java, 84 bytes
int[]r(int[]A,int K){for(int i=0;i<A.length;A[i++]+=Math.random()>.5?0:K);return A;}
Ungolfed
int[] r(int[] A, int K) {
for (int i = 0;
i < A.length;
A[i++] += Math.random() > .5 ? 0 : K);
return A;
}
Notes
- The afterthought of the loop could also be it's body, there is no difference in size.
- The input array is modified but the statement does not contain a restriction regarding this issue. If you would count the modified array as a form of "Output/return", you could shave off another 9 bytes by removing
return A;
. The return type would need to be changed fromint[]
tovoid
. This however does not save additional bytes since an additional space is needed betweenvoid
andr
.
Shorter version (As mentioned in the note), 75 bytes
void r(int[]A,int K){for(int i=0;i<A.length;)A[i++]+=Math.random()>.5?0:K;}
Output
[1, 2, 3, 4], 0 => [1, 2, 3, 4]
[1, 2, 3, 4], 1 => [1, 3, 3, 4]
[1, 2, 3, 4], 2 => [3, 2, 3, 4]
[1, 2, 3, 4], 3 => [4, 5, 3, 7]
[1, 2, 3, 4], 4 => [5, 2, 3, 8]
[1, 2, 3, 4], 5 => [6, 2, 8, 9]
-
\$\begingroup\$ Your second version isn't valid, it doesn't output nor return anything. \$\endgroup\$Bálint– Bálint2016年04月30日 17:46:22 +00:00Commented Apr 30, 2016 at 17:46
-
1\$\begingroup\$ Please read my post... \$\endgroup\$Marv– Marv2016年04月30日 17:47:32 +00:00Commented Apr 30, 2016 at 17:47
Mathcad, bytes
No formal byte count as Mathcad counting protocol yet to be decided.
Java (削除) 108 (削除ここまで) (削除) 107 (削除ここまで) (削除) 85 (削除ここまで) 82 bytes
void f(int[]s,int k){for(int i:s)System.out.print((i+=Math.random()<.5?k:0)+";");}
14 bytes saved thanks to @TimmyD
-
\$\begingroup\$ @TimmyD The rules say you need to output it. And that rule wasn't like that, when I wrote the answer \$\endgroup\$Bálint– Bálint2016年04月29日 19:49:29 +00:00Commented Apr 29, 2016 at 19:49
-
\$\begingroup\$ I believe you can remove the space after
main
,String[]
,int[]
, and save another few bytes by changingnextFloat()>0.5
tonext(1)==0
. \$\endgroup\$anon– anon2016年04月29日 19:49:44 +00:00Commented Apr 29, 2016 at 19:49 -
\$\begingroup\$ @QPaysTaxes I already change
new java.util.Random().nextFloat()
toMath.random()
, as it is much much shorter. \$\endgroup\$Bálint– Bálint2016年04月29日 19:51:55 +00:00Commented Apr 29, 2016 at 19:51 -
\$\begingroup\$ This does not work in it's current state. You don't modify
s
, only thei
, the method has return typevoid
but you are trying to returnint[]
. Also theres a semicolon missing afterreturn s
. \$\endgroup\$Marv– Marv2016年04月30日 14:49:01 +00:00Commented Apr 30, 2016 at 14:49
[0,1)
typo? 2 more to go... \$\endgroup\$x
such that0 ≤ x < 1
. \$\endgroup\$