Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I was trying with String Functions and I viewing any posts and have no results

I want to know

1.- From

cromo33 = Table[RandomInteger[], {i, 1, 33}]
cromo33

that gives {1,0,1,1,1,0,1,......,1,0,0} , alist of 33 elements

How can you obtain "1011101.....100" ?

2.- From

IntegerString[RandomInteger[8], 2] // InputForm

that gives 101 (a little add-on... ¿how can I force this to obtain 4 digits in any random number?)

How can you obtain a list {1,0,1} ?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

There are built-in functions to play:

NumberForm[FromDigits@RandomInteger[1, 5], 6, NumberPadding -> "0"]
"0011101"

Or very straightforward approach:

1

RandomInteger[1, 5]
PadLeft[%, 7]
ToString /@ %
StringJoin@% 
{0, 1, 0, 1, 0}
{0, 0, 0, 1, 0, 1, 0}
{"0", "0", "0", "1", "0", "1", "0"}
"0001010"

2

IntegerString[RandomInteger[8], 2]
Characters@%
PadLeft[%, 4]
ToExpression@%
"101"
{"1", "0", "1"}
{0, "1", "0", "1"}
{0, 1, 0, 1}
share|improve this answer
    
I love this kind of answers, with multiple and simply solutions. Thanks –  Mika Ike Mar 23 at 6:46
    
The only option I miss is from "101" to 101, and viceversa. –  Mika Ike Mar 23 at 7:19
1  
@MikaIke It's ToExpression and ToString :) And thanks, I'm glad you like it :) –  Kuba Mar 23 at 8:07

Just some other functions to consider:

  • IntegerDigits an take a base argument, e.g. IntegerDigits[5,2] yields {1,0,1}
  • FromDigits is the inverse: FromDigits[{1,0,1},2] yields 5
  • If the issue is for display purpose and not specifically need for strings then BaseForm will display binary numbers with subscript of 2, i.e.BaseForm[5,2] yields: $101_2$
  • so for first part if display is aim you can use (perhaps somewhat perversely) BaseForm[ToExpression@Table[RandomInteger[], {i, 1, 33}]]
share|improve this answer
    
is for work with cromosomas en genetic algorithms –  Mika Ike Mar 23 at 7:20
    
@MikaIke thank you for clarification. All the best in your endeavours. –  ubpdqn Mar 23 at 7:36
    
Thank you, it´s my final project in maths grade/degree –  Mika Ike Mar 23 at 7:40

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.