Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Assign a value to a variable

  • To: mathgroup at smc.vnet.net
  • Subject: [mg63039] Re: [mg62996] Assign a value to a variable
  • From: "David Park" <djmp at earthlink.net>
  • Date: Sun, 11 Dec 2005 04:57:34 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

Ben,

The quick answer is to Evaluate the lhs of the Set statement.

vars = {a, b, c, d, e, f, g, h, i};
numbers = Range[9];

Evaluate[vars[[Random[Integer,
     {1, Length[vars]}]]]] =
  numbers[[Random[Integer, {1, Length[numbers]}]]]
vars

But are you going to evaluate it repeatedly? Then you will get an error if a
variable is already assigned. You could do something like this...

randomAssign[vars_?VectorQ, nums_?VectorQ] :=
  Module[
    {ranvar = Random[Integer, {1, Length[vars]}],
      rannum = Random[Integer, {1, Length[vars]}],
      x, y},
    y = Part[vars, ranvar];
    x = Part[nums, rannum];
    If[Head[y] === Symbol, Evaluate[y] = x];
    ]

randomAssign[vars, numbers]
vars

Or maybe you want to Drop the entries from each of the lists with each
assignment. You could then use the following...

ClearAll[randomAssign];
Attributes[randomAssign] = {HoldAll};
randomAssign[vars_?VectorQ, nums_?VectorQ] :=
  Module[
    {ranvar, rannum, x, y},
    If[Length[vars] == 0 \[And] Length[nums] == 0, Return[]];
    ranvar = Random[Integer, {1, Length[vars]}];
    rannum = Random[Integer, {1, Length[vars]}];
    y = Part[vars, ranvar];
    x = Part[nums, rannum];
    Evaluate[y] = x;
    vars = Drop[vars, {ranvar}];
    nums = Drop[nums, {rannum}];
    ]

Clear[a, b, c, d, e, f, g, h, i]
vars = {a, b, c, d, e, f, g, h, i};
numbers = Range[9];

randomAssign[vars, numbers]
{a, b, c, d, e, f, g, h, i}
vars

The last statements can be evaluated repeatedly until all variables are
assigned.

David Park
djmp at earthlink.net
http://home.earthlink.net/~djmp/



From: Ben Becker [mailto:ben.becker at gmx.de]
To: mathgroup at smc.vnet.net


Hi!

I have a list of variables:
vars = {a, b, c, d, e, f, g, h, i}

and a list of numbers:
numbers = Range[9]

Now i'd like to choose randomly a variable and a number. and then i'd
like to assign the number to the variable.
I thought of somehting like that:

vars[[Random[Integer, {1, Length[vars]}]]] =
numbers[[Random[Integer, {1, Length[numbers]}]]]

but it doesn't work.

i hope you have an idea!

thank you for answering!

MFG Ben



  • Prev by Date: Re: functional programming
  • Next by Date: Re: Re: Using The Random Function to predict Things
  • Previous by thread: Re: Assign a value to a variable
  • Next by thread: A list of numbers without "73"