Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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]
share|improve this question
    
[0,1) typo? 2 more to go... – epicTCK yesterday
5  
Does the random choice have to be determined by float comparison or can we pick at random? – Alex A. yesterday
    
Can I post a program, or can it be a function? It makes a very distibguishable differebce in java. – Bálint yesterday
1  
@epicTCK That means a half-open interval, i.e. a real number x such that 0 ≤ x < 1. – Martin Büttner yesterday
1  
@Bálint Both notations exist. – Martin Büttner yesterday

18 Answers 18

Jelly, 9 8 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).
share|improve this answer
    
How in the he-double-L do you successfully keyboard in this language?! – MonkeyZeus yesterday
    
@MonkeyZeus Dennis said, it can be entered on Linux using a normal keyboard. – Bálint yesterday
    
@Bálint The plot thickens, who is Dennis? lol – MonkeyZeus yesterday
10  
@MonkeyZeus Ahem. – Dennis yesterday
1  
@Dennis The prophecy has been fulfilled ┗( ⊙ .⊙ )┛ – MonkeyZeus yesterday

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!

share|improve this answer
    
An anonymouse function will suffice in this case, but nice answer; welcome to PPCG! – cat yesterday

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
+      % add element-wise
share|improve this answer
1  
Typed from phone. Explanation later – Luis Mendo yesterday
1  
Later=now? ..... – CatsAreFluffy yesterday
    
@CatsAreFluffy :-) Done! – Luis Mendo yesterday

Python 2, 60 bytes

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.

share|improve this answer
1  
@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 1 hour ago
    
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 1 hour ago
    
@FryAmTheEggman Oh haha, I didn't notice. I'll do that now, thanks :) – undergroundmonorail 12 mins ago

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

share|improve this answer
2  
floating point is floating point >:( – Kenny Lau yesterday
1  
@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 yesterday
    
@KennyLau what about languages without floating points? – ven yesterday
    
@FryAmTheEggman Yes, it was just an example--equal probability is fine. – Cᴏɴᴏʀ O'Bʀɪᴇɴ yesterday
    
@KennyLau The OP has confirmed that floating point isn't necessary. – Alex A. yesterday

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.

Try it online!

Saved 2 bytes thanks to Dennis!

share|improve this answer

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

share|improve this answer
    
I want to participate in a challenge and...javascript is taken. Seriously, I'll learn unary. – Bálint yesterday
    
@Bálint i'm pretty sure unary can't generate random floats – undergroundmonorail yesterday
    
@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 yesterday

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.

share|improve this answer

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.

share|improve this answer

Ruby, 28 bytes

->a,k{a.map{|e|e+k*rand(2)}}
share|improve this answer

php 71 bytes

function f($s,$k){foreach($s as $v){$v+=rand(0,2)==0?k:0;echo $v.",";}}
share|improve this answer

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
share|improve this answer
    
Nice, including a general version! – Cᴏɴᴏʀ O'Bʀɪᴇɴ 2 hours ago

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.

share|improve this answer
1  
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 – Cᴏɴᴏʀ O'Bʀɪᴇɴ 23 hours ago
    
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 5 hours ago

Octave, 28 bytes

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

Sample run on ideone.

share|improve this answer

05AB1E, 10 bytes

Code:

vždɲ*y+})

Try it online!.

share|improve this answer

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]
share|improve this answer
    
Your second version isn't valid, it doesn't output nor return anything. – Bálint 5 hours ago
    
Please read my post... – Marv 5 hours ago

Mathcad, bytes

enter image description here


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

share|improve this answer

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

share|improve this answer
    
@TimmyD The rules say you need to output it. And that rule wasn't like that, when I wrote the answer – Bálint yesterday
    
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. – QPaysTaxes yesterday
    
@QPaysTaxes I already change new java.util.Random().nextFloat() to Math.random(), as it is much much shorter. – Bálint yesterday
    
@TimmyD Didn't see that, thanks – Bálint yesterday
    
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 8 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.