# Run through an array

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!

1. Let e be the current element.
2. Let random generate a random float in [0,1). If random() < 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.)
3. Otherwise, you perform function f on e.

## 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 , 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]

• [0,1) typo? 2 more to go... – Bald Bantha Apr 29 '16 at 17:04
• Does the random choice have to be determined by float comparison or can we pick at random? – Alex A. Apr 29 '16 at 17:09
• Can I post a program, or can it be a function? It makes a very distibguishable differebce in java. – Bálint Apr 29 '16 at 17:12
• @epicTCK That means a half-open interval, i.e. a real number x such that 0 ≤ x < 1. – Martin Ender Apr 29 '16 at 17:12
• @Bálint Both notations exist. – Martin Ender Apr 29 '16 at 17:14

# Pyth, 7

m+*O2vz


Try it here

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


Try it here

• floating point is floating point >:( – Leaky Nun Apr 29 '16 at 17:00
• @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. – FryAmTheEggman Apr 29 '16 at 17:09
• @KennyLau what about languages without floating points? – Ven Apr 29 '16 at 17:12
• @FryAmTheEggman Yes, it was just an example--equal probability is fine. – Conor O'Brien Apr 29 '16 at 18:40
• @KennyLau The OP has confirmed that floating point isn't necessary. – Alex A. Apr 29 '16 at 18:41

# 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!

• An anonymouse function will suffice in this case, but nice answer; welcome to PPCG! – cat Apr 29 '16 at 22:41
• Many times for is shorter than map, 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 #(. – NikoNyrh Dec 26 '16 at 20:49

# Jelly, 98 7 bytes

From 8 to 7 thanks to @FryAmTheEggman.

+2X’¤¡€


Try it online!

### 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).

• How in the he-double-L do you successfully keyboard in this language?! – MonkeyZeus Apr 29 '16 at 19:39
• @MonkeyZeus Dennis said, it can be entered on Linux using a normal keyboard. – Bálint Apr 29 '16 at 19:52
• @Bálint The plot thickens, who is Dennis? lol – MonkeyZeus Apr 29 '16 at 20:11
• @MonkeyZeus Ahem. – Dennis Apr 29 '16 at 20:29
• @Dennis The prophecy has been fulfilled ┗( ⊙ .⊙ )┛ – MonkeyZeus Apr 29 '16 at 20:39

# MATL, 11 bytes

tZy1$rEki*+  Uses floating point random numbers. Try it online! ### 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

• Typed from phone. Explanation later – Luis Mendo Apr 29 '16 at 17:48
• @CatsAreFluffy :-) Done! – Luis Mendo Apr 29 '16 at 22:33

# Japt, 6 bytes

®+V*Mq


Test it

## 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, 3329 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.

Try it online!

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
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]



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.

• @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]) – undergroundmonorail Apr 30 '16 at 21:57
• 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. – FryAmTheEggman Apr 30 '16 at 22:07
• @FryAmTheEggman Oh haha, I didn't notice. I'll do that now, thanks :) – undergroundmonorail Apr 30 '16 at 23:07

# 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)

• I want to participate in a challenge and...javascript is taken. Seriously, I'll learn unary. – Bálint Apr 29 '16 at 17:10
• @Bálint i'm pretty sure unary can't generate random floats – undergroundmonorail Apr 29 '16 at 17:34
• @undergroundmonorail I said it because no one uses it (for obvious reasons, like it can't be posted here because it becomes too long) – Bálint Apr 29 '16 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.

Test it here.

# 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

• Nice, including a general version! – Conor O'Brien Apr 30 '16 at 21:11

# Python 3 152110 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.

• 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 – Conor O'Brien Apr 29 '16 at 23:58
• You can put x[ptr]=z+y on the same line as if random()>0.5 to save 3 bytes of whitespace. In python 2 0.5 can be written as .5 to save a byte, I don't know if that's true in python 3 though. If you rename ptr to p 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 :) – undergroundmonorail Apr 30 '16 at 17:40

# Octave, 28 bytes

@(A,R)R*(rand(size(A))<.5)+A


Sample run on ideone.

# 05AB1E, 10 bytes

Code:

vždÉ²*y+})


# 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 from int[] to void. This however does not save additional bytes since an additional space is needed between void and r.

### 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]

• Your second version isn't valid, it doesn't output nor return anything. – Bálint Apr 30 '16 at 17:46
• Please read my post... – Marv Apr 30 '16 at 17:47

No formal byte count as Mathcad counting protocol yet to be decided.

# Java 10810785 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

• @TimmyD The rules say you need to output it. And that rule wasn't like that, when I wrote the answer – Bálint Apr 29 '16 at 19:49
• I believe you can remove the space after main, String[], int[], and save another few bytes by changing nextFloat()>0.5 to next(1)==0. – Nic Hartley Apr 29 '16 at 19:49
• @QPaysTaxes I already change new java.util.Random().nextFloat() to Math.random(), as it is much much shorter. – Bálint Apr 29 '16 at 19:51
• @TimmyD Didn't see that, thanks – Bálint Apr 29 '16 at 20:07
• This does not work in it's current state. You don't modify s, only the i, the method has return type void but you are trying to return int[]. Also theres a semicolon missing after return s. – Marv Apr 30 '16 at 14:49

## 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.

# Perl 5, 30 + 1 (-a) = 31 bytes

$,=<>;say.5>rand?$_:$_+$,for@F


Try it online!