3
$\begingroup$

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} ?

$\endgroup$
3
$\begingroup$

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}
$\endgroup$
  • $\begingroup$ I love this kind of answers, with multiple and simply solutions. Thanks $\endgroup$ – Mika Ike Mar 23 '14 at 6:46
  • $\begingroup$ The only option I miss is from "101" to 101, and viceversa. $\endgroup$ – Mika Ike Mar 23 '14 at 7:19
  • 1
    $\begingroup$ @MikaIke It's ToExpression and ToString :) And thanks, I'm glad you like it :) $\endgroup$ – Kuba Mar 23 '14 at 8:07
4
$\begingroup$

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}]]
$\endgroup$
  • $\begingroup$ is for work with cromosomas en genetic algorithms $\endgroup$ – Mika Ike Mar 23 '14 at 7:20
  • $\begingroup$ @MikaIke thank you for clarification. All the best in your endeavours. $\endgroup$ – ubpdqn Mar 23 '14 at 7:36
  • $\begingroup$ Thank you, it´s my final project in maths grade/degree $\endgroup$ – Mika Ike Mar 23 '14 at 7:40
1
$\begingroup$

Let:

SeedRandom[11]

cromo33 = RandomInteger[1, 33];

To produce your string I would use Row and ToString:

ToString @ Row @ cromo33
"001101111011110111010011001000101"

For the second case IntegerString takes a third parameter that specifies length:

SeedRandom[15]
string = IntegerString[RandomInteger[8], 2, 4]
"0101"

To convert this back into to a digit list I propose ToCharacterCode:

ToCharacterCode[string] - 48
{0, 1, 0, 1}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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