Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

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

Generate a cipher given a number and string

Your task is simple. Given a string s and a number 0 <= n <= 9 as inputs, insert a pseudo-random printable ASCII character between each character of the string n times. Such that for each character of s there are n random characters between them. Spaces should be trimmed.

Input:

  • string s phrase to encrypt in the cipher
  • integer n in the range of 0 <= n <= 9

Example:

Input:

The treasure is here
2

Output:

T!0h32eF4t0irlkehma7ys#0u*&r*he!2iH^sB,h!@e0)r$he


This is so the shortest code wins! Good Luck and have fun!

share|improve this question
1  
Do each individual character need to be random or can there be a set of n unique random ascii characters between the letters (no duplicate random characters between the letters)? – Emigna 4 hours ago
1  
random printable ASCII character You need to define what random means here. Shold all printable ASCII characters have the same probability? Should they be statistically independent? What flexibility do we have regarding this? – Luis Mendo 3 hours ago
1  
@Yodle Yes that is acceptable – jacksonecac 3 hours ago
1  
@jacksonecac I disagree. Just saying random is not enough. For example, if I only pick random characters with even ASCII codes, that's still random but that's probably not accepted (or ist it?) If each series of n characters consists of n copies of the same random character, they are still random, but they are not statistically independent. And so on – Luis Mendo 2 hours ago
1  
@jacksonecac "random" is a very broad term. Can I choose the characters with a normal distribution, so that characters around O are more likely than spaces or ~? If it has to be uniform, then you should say so explicitly. And if it doesn't have to be uniform, then you should at least state something like each character needs to have a non-zero probability. You've also stated in a previous comment that each character does have to have an independent distribution, so if this is important, it should be mentioned in the challenge. There is a very broad spectrum of randomness. – Martin Ender 2 hours ago

11 Answers 11

Java 7, 132 124 bytes

String f(int n,char[]a){String o="";int i;for(char b:a)if(b>32)for(i=0,o+=b;i++<n;o+=(char)(33+Math.random()*94));return o;}

Nothing fancy, just a double loop like you'd expect. Outer to loop the string, inner to fill in randoms:

String f(int n,char[]a){
    String o="";
    int i;
    for(char b:a)
        if(b>32)
            for(i=0,
                o+=b;
                    i++<n;
                        o+=(char)(33+Math.random()*94));
    return o;
}
share|improve this answer
    
No need for k: String f(int n,char[]a){String o="";for(char b:a)if(b>32){o+=b;for(int i=0;i++<n;o+=(char)(33+Math.random()*94));}return o;} (125 bytes) – Olivier Grégoire 3 hours ago
    
Oooh right. I was using it with a different method. Didn't think about taking it out when I went with the char cast. Thanks! – Geobits 3 hours ago
    
My bad. I miscounted, my suggestion was also 124 bytes: I checked the column instead of the length ;) – Olivier Grégoire 2 hours ago
    
Yeah, I noticed that when comparing the two :) – Geobits 2 hours ago

Python 2, 123 122 118 114 98 Bytes

Man, I wish random wasn't so expensive (and that we didn't have to filter for spaces). Now we have big savings from being allowed to have cipher characters at the end :) Anyways, here ya go:

from random import*
f=lambda s,n:s and(' '<s[0])*eval('s[0]'+'+chr(randint(32,126))'*n)+f(s[1:],n)
share|improve this answer

05AB1E, 11 bytes

ð-vy²FžQ.RJ

Try it online!

Explanation to come when I'm at a Computer.

share|improve this answer
    
close! trim the spaces! :) – jacksonecac 4 hours ago
    
@jacksonecac: Missed that part sorry. Fixed now :) – Emigna 4 hours ago
    
nice job! that works! – jacksonecac 4 hours ago
1  
@carusocomputing: That adds random characters after the last letter as well. Not just in between letters. – Emigna 3 hours ago
1  
@Emigna After a recent comment under the question this seems to be fine :) – geisterfurz007 3 hours ago

Octave, 39 bytes

@(s,n)[s;32+94*rand(n,nnz(s))](1:end-n)

This takes a string s and an integer n as input. A string in Octave is simply an array of characters. It appends a matrix with n rows and the same number of columns as s has, containing floating point numbers between 32 and 126. It is implicitly rounded to integers and converted to ASCII-characters when it's concatenated with the string s. (1:end-n) straightens this to a horizontal array of characters, where the last n elements are removed.

Test it here!

share|improve this answer
1  
Implicit rounding! Nice – Luis Mendo 3 hours ago
    
I just noticed that challenge says spaces should be trimmed. Not that it really adds anything to the challenge, and I'm not even sure what it means exactly, but... – Luis Mendo 1 hour ago

C#, 141 131 bytes

Pretty similar to @Geobit's Java answer, except longer currently :(

(I,n)=>{var R=new System.Random();var o="";int i,r;foreach(var c in I)if(c>32)for(i=r=0,o+=c;i++<n;){r=R.Next(33,127);o+=(char)r;}return o;};

Full lambda stuff:

Func<string, int, string> a = (I,n) =>
{
    var R=new System.Random();
    var o="";
    int i;
    foreach(var c in I)
        if(c>32)
            for(i=0,o+=c;i++<n;o+=(char)R.Next(33,127));
    return o;
};
share|improve this answer
    
why R=... You can just directly use new System.Random().Next(...) I think – Roman Gräf 2 hours ago
1  
@RomanGräf msdn.microsoft.com/en-us/library/h343ddh9(v=vs.110).aspx C#'s Random class, without a seed, will use the System clock, so if you call in rapid succession (such as within the loop there), most of the values end up being identical, which wouldn't work in most cases :( Believe me, I always try and then remember that. – Yodle 2 hours ago

CJam, 21 18 bytes

lS-(ol~f{{95mrSc+\}*}

Try it online!

Prints n random trailing characters.

Explanation

lS-        e# Read line and remove spaces.
l~         e# Read and evaluate another line.
f{         e# For each character (passing in N)...
  {        e#   Do this N times...
    95mr   e#     Push random integer in [0, 95).
    Sc+    e#     Add to space character, giving a random printable ASCII character.
  }*
}
           e# All characters remaining on the stack are printed implicitly
           e# at the end of the program.
share|improve this answer

Pyke, 12 11 9 bytes

d-FQV~KHs(<

Try it here!

d-        -  remove spaces from input
  F       - for i in ^:
   QV     -  repeat (number) times:
     ~KH  -    random_from(printable)
        s -   sum(^)

Trailing random characters is fine according to OP.

share|improve this answer

JavaScript (Firefox 30+), 101 bytes

(s,n)=>s.replace(/. *(?=.)/g,x=>x[0]+String.fromCharCode(...[for(_ of Array(n))Math.random()*95+32]))

Pure ES6 is two bytes longer:

(s,n)=>s.replace(/. *(?=.)/g,x=>x[0]+String.fromCharCode(...[...Array(n)].map(_=>Math.random()*95+32)))
share|improve this answer

R, 97 bytes

Unnamed function taking inputs x (string) and n.

function(x,n,l=nchar(x))for(i in 1:l)cat(substr(x,i,i),if(i<l)intToUtf8(sample(32:126,n)),sep="")

Try it on R-fiddle

share|improve this answer

Q/KDB+, 39 36 Bytes

raze{""sv(raze x;`char$40+n?87)}prior s

(,/)({""sv((,/)x;`char$40+n?87)}':)s

Variables in use:

s:"The treasure is here"
n:2

This uses the prior adverb, which applies the function to it's left between each item to the right and its predecessor. (Essentially, applies function to the left between each character on the right.)

Generate n random numbers between 40 and 126 then convert them to a character equivilent: (q seems to only have characters for these)

`char$40+n?87

//Possible characters.
()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Example output:

TVghrveVp Rpti+r0sea3a9nsIjuRXrAReJ; +di=ys`{ ikhKTe4trTZesz

EDIT:
Saved 3 bytes by converting q's raze into (,/) using the k notation and similarly changed prior to `:

share|improve this answer
    
can save a couple of bytes by casting with 10h$ – slackwear 12 mins ago

Bash, 124 bytes

Pure bash + coreutils, no control flow structures, no sub-languages, no "eval"

Golfed

E() { N=${1// /};paste <(fold -1<<<$N) <(tr -cd "\\40-\\176"<\/dev\/urandom|head -c$(($2*${#N}-$2))|fold -$2)|tr -d '\t\n';}

Test

>E "The treasure is here" 2
TkZhf(e&Rt@FrS,edha+-sJTuh.rX@eVKi+3s<7hftey8r*/e
share|improve this answer

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.