Numbers Manipulation challenge

5

1

Use any programming language to generate two random digits between 1 and 9 (including both). Then your program should display:

  • in the first line: the first random digit,
  • in the second line: the second random digit,
  • in the third line: a number whose tens and units digits are the first and second random digits respectively,
  • in the fourth line: the number from the third line raised to the power of 2.

For example, if digits "9" and "2" were generated, your program should display exactly:

9
2
92
8464

Monolica

Posted 2018-10-31T11:51:06.413

Reputation: 1 101

12Can we output an array? – Quintec – 2018-10-31T11:57:15.047

3Can we sample without replacement, ie exclude 1,1 2,2 3,3... from the pairs? – JayCe – 2018-10-31T13:57:00.297

2(i.e., what's the distribution of the random numbers?) – user202729 – 2018-10-31T16:11:23.040

You should probably specify that the digits are pairwise independent and uniformly random. Otherwise, one can go with a degenerate distribution and write "cat (10 Bytes): 1[newline]1[newline]11[newline]121" – Yonatan N – 2018-11-02T00:23:08.223

@YonatanN The standard assumption on PPCGcfor the term random is that all possibilities have a non-zero chance of occuring. – Jo King – 2018-11-02T12:47:21.710

Why did you accept my answer just yet, when there are two 9-byte solutions that are shorter? For code-golf challenges you should accept the shortest one (and sometimes the earliest edit/post if there are more than one shortest), or don't accept an answer at all. – Kevin Cruijssen – 2018-11-21T07:30:48.070

Answers

2

05AB1E, 14 11 bytes

2F9LΩ=}J=n,

-3 bytes thanks to @Emigna.

Try it online.

Explanation:

2F    }        # Loop 2 times:
  9LΩ          #  Create a list in the range [1,9], and pick a random element from it
     =         #  Output it (without popping it from the stack)
       J       # Join them together
        =      # Output it (without popping it from the stack)
         n     # Take it to the power of 2
          ,    # And output it as well

11 bytes alternative:

9LãΩ©`®JDn»

Try it online.

Explanation:

9L             # List in the range [1,9]
  ã            # Cartesian product with itself: [[1,1],[1,2],[1,3],...,[9,7],[9,8],[9,9]]
   Ω           # Take a random element from it
    ©          # Store it in the register (without popping)
     `         # Pop and push both items as separated items onto the stack
      ®        # Retrieve the list of digits from the register again
       J       # Join them together to a single 2-digit number
        Dn     # Duplicate it, and take the power of 2 of the copy
          »    # Merge all values on the stack by newlines (and output implicitly)

Kevin Cruijssen

Posted 2018-10-31T11:51:06.413

Reputation: 67 575

1Shorter in a looP: 2F9LΩ=}J=n, – Emigna – 2018-10-31T12:01:32.343

@Emigna I was about to look for shorter alternatives, but smart use of the =! – Kevin Cruijssen – 2018-10-31T12:04:28.583

6

R, 48 47 bytes

cat(x<-sample(9,2,T),y<-x%*%c(10,1),y^2,fill=1)

Try it online!

Thanks to J.Doe for golfing down a byte.

Giuseppe

Posted 2018-10-31T11:51:06.413

Reputation: 21 077

Tweak to cat args. 47 bytes

– J.Doe – 2018-11-03T19:24:08.060

@J.Doe thanks! Probably there are other submissions where fill would be handy... – Giuseppe – 2018-11-03T22:32:13.347

5

Japt, 14 13 bytes

-1 Byte from @Oliver

2ÆÒ9ö
pU¬Uì ²

2ÆÒ9ö
pU¬Uì ²     Full program
-----------------------------------------
2Æ            Range [0,2) and map 
   9ö         Random number in range [0, 9)
  Ò           increased by 1
              This result is assigned to U

p            Push into U    
 U¬          Elements in U joined
   Uì ²      and elements joined squared
             Implicit output each element 
             separated with new line -R

Try it online!

Luis felipe De jesus Munoz

Posted 2018-10-31T11:51:06.413

Reputation: 9 639

1You can use 2ÆÒ9ö to save a byte on the first line. – Oliver – 2018-10-31T17:33:36.003

5

Vim, 43 bytes

:%!$RANDOM

:s/0//g
2f:y2hVpo<C-r>=<C-r>0*<C-r>0
<Esc>kYPa

Try it online!

Not the right tool for the job. This produces most likely the desired output

Step by step:

  • :%!$RANDOM Enter Enter
    Produces a string like /bin/bash: 25266: command not found

  • :s/0//g
    removes all zeroes

  • 2f:y2hVp
    moves the cursor to the colon after the number, copy the last two digits and replace the entire string with those

  • o Ctrl+R = Ctrl+R 0* Ctrl+R 0 Enter
    add a new line and evaluate an expression. In this case, I'll multiply the number in register 0 (the one that was just copied) with itself.

  • Esc kYPa Enter
    Copy the upper line and paste it above. The cursor ends up in the first line, on the first character. Now we just have to append a line break to it

Limitations: If the result of $RANDOM is a number with less than two non-zero digits, this will not produce the desired output

oktupol

Posted 2018-10-31T11:51:06.413

Reputation: 697

4

C (gcc), 68 67 bytes

-1 byte thanks to cleblanc

f(r){r=rand()%81*10/9+11;printf("%d\n%d\n%d\n%d",r/10,r%10,r,r*r);}

Try it online!

nwellnhof

Posted 2018-10-31T11:51:06.413

Reputation: 10 037

save one byte using r;f() --> f(r) – cleblanc – 2018-10-31T13:10:43.043

4

K (oK), 28 bytes

t:2?10;t,:10/t;$t,:t[2]*t[2]

Explanation

t:2?10                       //define t as two random numbers from 1-10
       t,:10/t               //join the base 10 joining of the elements of t to t
                 t,:t[2]*t[2]//join the square of the index 2 element to t
               $            //String each element of the result (to output on newlines)

Try it online!

Cleaner Output, 32 bytes

t:2?10;t,:10/t;`0:$t,:t[2]*t[2];

               `0:               //Cleanly prints the strings

Try it online!

Thaufeki

Posted 2018-10-31T11:51:06.413

Reputation: 421

1

If we're allow to return an array then a,b,b*b:10/a:1+2?9 for 18 chars Try it online!

– streetster – 2018-10-31T19:00:56.927

+1 Much neater, its only the extra $ character to match the output of my first answer, with -9 bytes. I hadn't tried to fit it into one expression – Thaufeki – 2018-10-31T19:34:35.210

2?10 could generate a 0. the challenge requires 1-9. – ngn – 2018-11-01T07:05:36.137

2\0:$a,*\2#10/a:1+2?9;` (works in ngn/k too) – ngn – 2018-11-01T07:09:49.213

That works great in ok, the issue with it in ngn/k is that it seems to generate the same output on every run – Thaufeki – 2018-11-02T14:40:21.283

1@Thaufeki the random seed in ngn/k predetermined, like in the original k – ngn – 2018-12-04T09:57:44.507

oh ok cool, thanks for the response! – Thaufeki – 2018-12-04T19:26:08.927

3

Python 3, 83 76 bytes

-5 bytes thanks to nwellnhof.

from random import*
k=randint(9,89)*10//9+1
[*map(print,[k//10,k%10,k,k*k])]

Try it online!

ovs

Posted 2018-10-31T11:51:06.413

Reputation: 21 408

82 bytes. – Erik the Outgolfer – 2018-10-31T14:00:47.540

3

Perl 6, 39 bytes

{.comb,$_,$_²}([~] roll 1..9: 2)>>.put

Try it online!

nwellnhof

Posted 2018-10-31T11:51:06.413

Reputation: 10 037

3

JavaScript (ES6), 67 bytes

f=_=>(n=Math.random()*90+10|0)%10?(n/10|0)+`
${n%10}
${n}
`+n*n:f()

Try it online!

Arnauld

Posted 2018-10-31T11:51:06.413

Reputation: 111 334

3

PowerShell, 48 45 bytes

($a,$b=1..9*2|Random -c 2)
($x="$a$b")
+$x*$x

Try it online!

Concatenates two ranges 1..9 together, pipes that to Get-Random with a -count of 2 to pull out two elements, stores them into $a and $b, and encapsulates that in parens to place a copy of them on the pipeline.

Next we string concatenate $a$b and store it into $x, again placing in parens to put a copy on the pipeline. Finally we take $x squared and leave it on the pipeline.

All the results are gathered from the pipeline and an implicit Write-Output gives us newlines between elements for free.

Saved 3 bytes thanks to mazzy.

AdmBorkBork

Posted 2018-10-31T11:51:06.413

Reputation: 41 581

1Smart get-random – mazzy – 2018-10-31T14:07:25.470

I think 1..9|Random -c 2 completely satisfies the condition two random digits between 1 and 9 (including both) – mazzy – 2018-11-01T11:22:21.493

...if not, then 1..9*2 is shorter – mazzy – 2018-11-01T11:25:13.243

1@mazzy Other answers seem to pick the two digits with replacement, so I did so as well. Thanks for the 1..9*2 golf! – AdmBorkBork – 2018-11-02T12:31:43.047

3

Jelly, 10 9 bytes

9ṗ2XṄ€ḌṄ²

Try it online!

How it works

9ṗ2XṄ€ḌṄ²  Main link. No arguments.

9          Set the return value to 9.
 ṗ2        Promote 9 to [1, ..., 9] and take the second Cartesian power, yielding
           [[1, 1], [1, 2], ..., [9, 8], [9, 9]].
   X       Pseudo-randomly select one of the pairs.
    Ṅ€     Print each integer in the pair, followed by a newline.
      Ḍ    Undecimal; convert the integer pair from base 10 to an integer.
       Ṅ   Print the integer, followed by a newline.
        ²  Take the square.
           (implicit) Print the last return value.

Dennis

Posted 2018-10-31T11:51:06.413

Reputation: 196 637

3

Pyth, 14 bytes

^
i,
hO9
hO9T2

Note that the newlines are significant. Try it online here.

Explanation, with newlines replaced with ¶ character:

^¶i,¶hO9¶hO9T2   Implicit: T=10

      O9         Choose a random number in [0-9)
     h           Increment
    ¶            Output with newline - value printed is yielded as expression result
        ¶hO9     Do the above again
   ,             Wrap the two previous results in a two-element array
  i         T    Convert to decimal from base 10
 ¶               Output with newline
^            2   Square the previous result, implicit print

Sok

Posted 2018-10-31T11:51:06.413

Reputation: 5 592

2@Downvoter - any particular reason why? – Sok – 2018-10-31T14:47:03.733

3

Ruby, 41 bytes

puts [(a=11+10*rand(81)/9)/10,a%10,a,a*a]

Try it online!

G B

Posted 2018-10-31T11:51:06.413

Reputation: 11 099

3

T-SQL, 142 105 115 114 96 78 bytes

DECLARE @ int=RAND()*9+1,@a int=RAND()*9+1SELECT @,@a,10*@+@a,POWER(10*@+@a,2)

-37 bytes: Realized I could just use two different random numbers and use the first digits from each!
+10 bytes: Edited to meet requirements of range from 1-9, instead of 0-9
-1 byte: Changed RIGHT() to LEFT() in @b
-18 bytes: Various changes suggested by BradC
-18 bytes: More changes suggested by BradC

Ungolfed:

-- Setting RAND() separately in these produces different numbers.
-- [RAND() * b + a] sets the range for a random number, from a to b inclusive.
-- Declaring as an int removes the numbers after the decimal.
DECLARE @ int = RAND() * 9 + 1,
        @a int = RAND() * 9 + 1

SELECT @,                       -- first random digit
       @a,                      -- second random digit
       10 * @ + @a,             -- multiply first digit by ten, and add second
       POWER(10 * @ + @a, 2)    -- third digit squared

Meerkat

Posted 2018-10-31T11:51:06.413

Reputation: 371

The stuff in the first comment definitely works, I'll edit that in. Problem with making the variables ints is that I would need to cast each individually as chars in the SELECT where necessary. With that, since each variable would need to be converted twice (in @+@a and POWER(@+@a,2)), it'd add more characters than it would save. – Meerkat – 2018-10-31T15:43:51.703

Good calls, thanks. Don't know why I didn't think of multiplying the first number by ten... – Meerkat – 2018-10-31T17:51:00.740

No problem, I'll delete my comments since you've incorporated them. – BradC – 2018-10-31T18:20:01.137

2

Python 2, 84 75 bytes

from random import*
k=randint(9,89)*10/9+1
for x in k/10,k%10,k,k*k:print x

Try it online!


Saved

  • -1 bytes, thanks to Erik the Outgolfer
  • -8 bytes, thanks to nwellnhof

TFeld

Posted 2018-10-31T11:51:06.413

Reputation: 19 246

Moderate golf: 83 bytes.

– Erik the Outgolfer – 2018-10-31T14:03:28.763

@EriktheOutgolfer Thanks :) – TFeld – 2018-10-31T15:10:08.563

2

Java 8, 99 98 90 81 80 bytes

v->{int i=81;i*=Math.random();return(i=i*10/9+11)/10+"\n"+i%10+"\n"+i+"\n"+i*i;}

-8 bytes after being inspired by @Arnauld's JavaScript answer.
-9 bytes thanks to @nwellnhof.

Try it online.

Explanation:

v->{                        // Method with empty unused parameter and no return-type
  int i=81;i*=Math.random();//  Create a random integer `i` in the range [0,81)
  return(i=i*10/9+11)       //  Set `i` to 10 times `i`, integer-divided by 9, and 11 added
        /10+"\n"            //  Return the first digit of `i`, a newline,
        +i%10+"\n"          //         the last digit of `i`, a newline,
        +i+"\n"             //         `i` itself, a newline,
        +i*i;}              //         and `i` multiplied by itself
                            //         All concatted to each other

Kevin Cruijssen

Posted 2018-10-31T11:51:06.413

Reputation: 67 575

2

Charcoal, 16 bytes

≔⭆²⊕‽⁹θ↓θθ⸿IXIθ²

Try it online! Link is to verbose version of code. Explanation:

≔⭆²⊕‽⁹θ

Generate two random characters in the range 1 to 9.

↓θ

Output them downwards i.e. on separate lines.

θ⸿

Output them horizontally on their own line.

IXIθ²

Cast to integer, square, cast back to string for implicit print.

Neil

Posted 2018-10-31T11:51:06.413

Reputation: 95 035

2

C# (.NET Core), 130 129 109 98 bytes

var r=new Random();int a=r.Next(1,10),b=r.Next(1,10),c=a*10+b;Console.Write($"{a} {b} {c} {c*c}");

Try it online!

-1 byte: edited console output to use wildcards (thanks to Logern)
-20 bytes: changed r to var from Random, changed format of c; fixed r.Next() operators (thanks to LiefdeWen)
-11 bytes: changed format of c (thanks to user51497)

Ungolfed:

var r = new Random();                   // initializes random number generator
int a = r.Next(1, 10),                  // gets random number between 1 and 9 inclusive
    b = r.Next(1, 10),                  // gets random number between 1 and 9 inclusive
    c = a * 10 + b;                     // concatenates a and b into one two-digit number
Console.Write($"{a} {b} {c} {c*c}");    // writes a, b, c, and c^2 to the console

Meerkat

Posted 2018-10-31T11:51:06.413

Reputation: 371

129 bytes-Try it online! – Logern – 2018-10-31T16:57:28.873

1109 bytes Also your .Next needs to include 10 so it can random 9 – LiefdeWen – 2018-11-01T12:54:13.347

@LiefdeWen Thanks. Didn't realize the max value of Random.Next() was exclusive. The min value is inclusive, though, so that needs to stay at 1 to fit the requirement of being between 1-9 inclusive. – Meerkat – 2018-11-01T13:07:49.370

1-11 bytes c = a*10 + b; – user51497 – 2018-11-01T15:57:29.663

2

This looks to be a snippet rather than a full function or program. Here is the guide to C# that should be able to help you turn your snippet into an acceptable answer.

– AdmBorkBork – 2018-11-09T13:56:34.127

@AdmBorkBork In reality, we're golfing against the language, and not against others, as C# cannot compete. There is a minimum number of required characters to create a C# program. See this comment.

– Meerkat – 2018-11-09T14:02:23.973

@Meerkat The entire program is not required, but you do need it to be in a function. That actually saves bytes then, because you can return rather than Console.Write ing – Skidsdev – 2018-11-09T14:06:13.687

94 bytes and a valid lambda function answer. (x is an unused input to save 1 byte, which is allowed as per PPCG standard rules) – Skidsdev – 2018-11-09T14:06:32.873

If you use the Visual C# Interactive Compiler (csi), you don't need the boilerplate. You'll have to replace the spaces in the output with newlines though. The challenge is rather specific about that.

– Dennis – 2018-11-09T14:08:15.753

Also by using Console.Write in the program I believe you also need to include the byte count of using System;, in which case it'd be shorter to specify System.Console.Write – Skidsdev – 2018-11-09T14:08:49.223

97 bytes with newlines – Skidsdev – 2018-11-09T14:09:25.017

Btw, csi lets you use Write instead of System.Console.Write and you don't need the trailing semicolon. 92 bytes

– Dennis – 2018-11-09T14:12:29.083

1

TI-BASIC, 27 bytes

11+int(89rand
Disp iPart(.1Ans),10fPart(.1Ans),Ans,Ans²

(can generate a 0 in the 2nd random number)

Uses kamoroso94's Disp layout, but makes use of TI-BASIC integer compression. Generating the 2 random integers as a single compressed integer and extracting them via iPart and fPart allows for shaving several bytes. It's possible to generate the random integers seperately in the same number of bytes by creating them simultaneously in a list:

1+int(9rand(2

But the repeated calls to the list via Ans(1) and Ans(2) end up taking many more bytes than the integer compression technique. It's also important to note that rand is generally advisable over randInt( for random integer generation as they either use equivalent bytes, or rand will be shorter when the lower bound is 0, and rand has the added flexibility of list generation.

TiKevin83

Posted 2018-10-31T11:51:06.413

Reputation: 121

This doesn't work; sometimes it generates 0 for the second digit. – lirtosiast – 2018-11-11T01:41:11.750

Yeah I see what I missed now, I don't think it's possible to improve from the 31 bytes and avoid the zeros then without messing with the output formatting. You can get 33 bytes by adding 2 randInt() and extracting them as shown here or 33 bytes again via the random list. – TiKevin83 – 2018-11-12T22:00:44.993

0

PHP, 64 bytes

<?$d=($c=(10*($a=rand(1,9))+$b=rand(1,9)))*$c;echo"$a
$b
$c
$d";

Try it online!

Jo.

Posted 2018-10-31T11:51:06.413

Reputation: 974

0

Retina, 43 bytes


100*
L$`
$.`
A`0
G?`..
\*\L`.
..
$.($&*$&*

Try it online! Explanation:


100*
L$`
$.`

Count from 0 to 99.

A`0

Delete multiples of 10.

G?`..

Pick a random 2-digit number.

*\L`.

Output the digits separately.

\

Output the number.

..
$.($&*$&*

Square and implicitly output the number.

Neil

Posted 2018-10-31T11:51:06.413

Reputation: 95 035

0

MBASIC, 100 86 bytes

1 DEF FNR(X)=INT(RND*X)+1:A=FNR(9):B=FNR(9):PRINT A:PRINT B:C=A*10+B:PRINT C:PRINT C^2

Output

5
8
58
3364

wooshinyobject

Posted 2018-10-31T11:51:06.413

Reputation: 171

0

TI-BASIC, 31 bytes

randInt(1,9→A
randInt(1,9→B
10A+B
Disp A,B,Ans,Ans²

kamoroso94

Posted 2018-10-31T11:51:06.413

Reputation: 739

0

sfk, 99 bytes

rand 1 9 +setvar a +rand 1 9 +setvar b +tell -var "#(a)
#(b)
#(a)#(b)" +calc -var #(a)#(b)*#(a)#(b)

Try it online!

Οurous

Posted 2018-10-31T11:51:06.413

Reputation: 7 916

0

perl -E, 45 bytes

$_=10+int rand 90;y/0/1/;say for/./g,$_,$_**2

This exploits the lack of a requirement that all random numbers should be picked with equal probability (it will pick numbers ending in 1 twice as often as ending in any other digit).

user73921

Posted 2018-10-31T11:51:06.413

Reputation:

0

Visual C#, 102 Bytes; 101 bytes

+2 Upper bound of Random.Next() exclusive, 10 instead of 9
-3 Thanks to LiefdeWen (var instead of Random)

var r=new Random();int x=r.Next(1,10),y=r.Next(1,10),z=x*10+y;Console.Write($"{x}\n{y}\n{z}\n{z*z}");

normal form:

var r = new Random();
int x = r.Next(1, 10), 
    y = r.Next(1, 10), 
    z = x * 10 + y;
Console.Write($"{x}\n{y}\n{z}\n{z * z}");

Try it online!

Visual C#, 85 bytes 89 bytes 91 Bytes

+4 bytes: fixed problem with 0 as second digits, borrowing the *10/9+1 from other answers

+2 bytes: preventing numbers <11

Even shorter solution

var r=new Random();int x=r.Next(9,89)*10/9+1;Console.Write($"{x/10}\n{x%10}\n{x}\n{x*x}");

normal form:

var r = new Random();
int x = r.Next(9, 89)*10/9+1;
Console.Write($"{x/10}\n{x%10}\n{x}\n{x*x}");

Try it online!

user51497

Posted 2018-10-31T11:51:06.413

Reputation: 113

98 bytes. You also had to include 10 in .Next to make 9 possible – LiefdeWen – 2018-11-01T12:51:06.620

0

Red, 69 bytes

prin reduce[x: random 9 n:"^/"y: random 9 n z: do rejoin[x y]n z * z]

Try it online!

Galen Ivanov

Posted 2018-10-31T11:51:06.413

Reputation: 13 815

0

MathGolf, 9 bytes

2æ8w)o§o²

Try it online!

Explanation

For the example, the first random integer is 4, the second is 7.

2æ         Start for-loop of length two, with the next 3 chars as the body
  8w       Random non-negative integer less than or equal to 8
    )      Increment by 1
     o     Output without popping (stack is unchanged)
           For loop ends, stack is now [4, 7], the first two lines have been printed
     §     Concatenate the two numbers on the stack (stack is [47])
      o    Output without popping (stack is unchanged)
       ²   Square number and output implicitly

maxb

Posted 2018-10-31T11:51:06.413

Reputation: 5 754

0

Batch, 95 bytes

@set/at=%random%%%9+1,u=%random%%%9+1,n=t*10+u,p=n*n
@for %%a in (%t% %u% %n% %p%)do @echo %%a

%random% isn't a real variable, it's interpolated at parse time, so you need the %s even inside set/a. (Also don't try using it in a loop!)

Neil

Posted 2018-10-31T11:51:06.413

Reputation: 95 035