15
\$\begingroup\$

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]
\$\endgroup\$
10
  • \$\begingroup\$ [0,1) typo? 2 more to go... \$\endgroup\$ Apr 29, 2016 at 17:04
  • 5
    \$\begingroup\$ Does the random choice have to be determined by float comparison or can we pick at random? \$\endgroup\$
    – Alex A.
    Apr 29, 2016 at 17:09
  • \$\begingroup\$ Can I post a program, or can it be a function? It makes a very distibguishable differebce in java. \$\endgroup\$
    – Bálint
    Apr 29, 2016 at 17:12
  • 1
    \$\begingroup\$ @epicTCK That means a half-open interval, i.e. a real number x such that 0 ≤ x < 1. \$\endgroup\$ Apr 29, 2016 at 17:12
  • 1
    \$\begingroup\$ @Bálint Both notations exist. \$\endgroup\$ Apr 29, 2016 at 17:14

23 Answers 23

5
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ An anonymouse function will suffice in this case, but nice answer; welcome to PPCG! \$\endgroup\$
    – cat
    Apr 29, 2016 at 22:41
  • \$\begingroup\$ 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 #(. \$\endgroup\$
    – NikoNyrh
    Dec 26, 2016 at 20:49
4
\$\begingroup\$

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).
\$\endgroup\$
5
  • \$\begingroup\$ How in the he-double-L do you successfully keyboard in this language?! \$\endgroup\$
    – MonkeyZeus
    Apr 29, 2016 at 19:39
  • \$\begingroup\$ @MonkeyZeus Dennis said, it can be entered on Linux using a normal keyboard. \$\endgroup\$
    – Bálint
    Apr 29, 2016 at 19:52
  • \$\begingroup\$ @Bálint The plot thickens, who is Dennis? lol \$\endgroup\$
    – MonkeyZeus
    Apr 29, 2016 at 20:11
  • 13
    \$\begingroup\$ @MonkeyZeus Ahem. \$\endgroup\$
    – Dennis
    Apr 29, 2016 at 20:29
  • 1
    \$\begingroup\$ @Dennis The prophecy has been fulfilled ┗( ⊙ .⊙ )┛ \$\endgroup\$
    – MonkeyZeus
    Apr 29, 2016 at 20:39
3
\$\begingroup\$

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

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

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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Typed from phone. Explanation later \$\endgroup\$
    – Luis Mendo
    Apr 29, 2016 at 17:48
  • \$\begingroup\$ @CatsAreFluffy :-) Done! \$\endgroup\$
    – Luis Mendo
    Apr 29, 2016 at 22:33
3
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Ruby, 28 bytes

->a,k{a.map{|e|e+k*rand(2)}}
\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
0
2
\$\begingroup\$

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.

\$\endgroup\$
3
  • 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\$ 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\$ Apr 30, 2016 at 22:07
  • \$\begingroup\$ @FryAmTheEggman Oh haha, I didn't notice. I'll do that now, thanks :) \$\endgroup\$ Apr 30, 2016 at 23:07
2
\$\begingroup\$

AWK, 56 bytes

x=NF{for(srand(systime());++i<x;)rand()>.5?$i+=$x:0}NF--

Try it online!

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.

\$\endgroup\$
1
  • \$\begingroup\$ The argument of srand() is optional. You can remove systime(), and still the random seed will follow the system date/clock. (According to gawk's and mawk's reference) \$\endgroup\$ Jun 4, 2021 at 7:22
1
\$\begingroup\$

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

\$\endgroup\$
3
  • \$\begingroup\$ I want to participate in a challenge and...javascript is taken. Seriously, I'll learn unary. \$\endgroup\$
    – Bálint
    Apr 29, 2016 at 17:10
  • \$\begingroup\$ @Bálint i'm pretty sure unary can't generate random floats \$\endgroup\$ 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
    Apr 29, 2016 at 17:45
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

php 71 bytes

function f($s,$k){foreach($s as $v){$v+=rand(0,2)==0?k:0;echo $v.",";}}
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Nice, including a general version! \$\endgroup\$ Apr 30, 2016 at 21:11
1
\$\begingroup\$

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.

\$\endgroup\$
2
  • 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\$ Apr 29, 2016 at 23:58
  • \$\begingroup\$ 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 :) \$\endgroup\$ Apr 30, 2016 at 17:40
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Factor, 29 bytes

[ '[ .5 [ _ + ] whenp ] map ]

Try it online!

  • '[ ... _ ... ] 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 of when that takes a probability instead of a boolean. In other words, there is a 50% chance that whenp's quotation will be called.
\$\endgroup\$
0
\$\begingroup\$

Octave, 28 bytes

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

Sample run on ideone.

\$\endgroup\$
0
\$\begingroup\$

05AB1E, 10 bytes

Code:

vždɲ*y+})

Try it online!.

\$\endgroup\$
0
\$\begingroup\$

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]
\$\endgroup\$
2
  • \$\begingroup\$ Your second version isn't valid, it doesn't output nor return anything. \$\endgroup\$
    – Bálint
    Apr 30, 2016 at 17:46
  • 1
    \$\begingroup\$ Please read my post... \$\endgroup\$
    – Marv
    Apr 30, 2016 at 17:47
0
\$\begingroup\$

Mathcad, bytes

enter image description here


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

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
5
  • \$\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
    Apr 29, 2016 at 19:49
  • \$\begingroup\$ 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. \$\endgroup\$
    – anon
    Apr 29, 2016 at 19:49
  • \$\begingroup\$ @QPaysTaxes I already change new java.util.Random().nextFloat() to Math.random(), as it is much much shorter. \$\endgroup\$
    – Bálint
    Apr 29, 2016 at 19:51
  • \$\begingroup\$ @TimmyD Didn't see that, thanks \$\endgroup\$
    – Bálint
    Apr 29, 2016 at 20:07
  • \$\begingroup\$ 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. \$\endgroup\$
    – Marv
    Apr 30, 2016 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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