I am having problem understanding how Random generators were suppose to work.
In the following example I'm trying to roll two dices on click,
https://ellie-app.com/d9rXQHpfJa1/1
but 'm getting
Function generate is expecting the 2nd argument to be:
Random.Generator ( Int, Int )
But it is:
( Random.Generator Int, Random.Generator Int )
The error message is giving you a strong hint that you are attempting to pass in a parameter that doesn't fit with what is expected. Elm does a lot of type inference and since NewFace (Int, Int) is a constructor that takes a tuple of two integers, that's what it expects for the second parameter passed to generate.
If you visit the Random package documentation, you'll see a function that takes two generators and gives you back a generator that uses the first two in a tuple. It is called Random.pair, and if you were to use it in your code, it would look like this:
( model, Random.generate NewFace (Random.pair (Random.int 1 6) (Random.int 1 6 )))
Related
I'm relatively new to Z3 and experimenting with it in python. I've coded a program which returns the order in which different actions is performed, represented with a number. Z3 returns an integer representing the second the action starts.
Now I want to look at the model and see if there is an instance of time where nothing happens. To do this I made a list with only 0's and I want to change the index at the times where each action is being executed, to 1. For instance, if an action start at the 5th second and takes 8 seconds to be executed, the index 5 to 12 would be set to 1. Doing this with all the actions and then look for 0's in the list would hopefully give me the instances where nothing happens.
The problem is: I would like to write something like this for coding the problem
list_for_check = [0]*total_time
m = s.model()
for action in actions:
for index in range(m.evaluate(action.number) , m.evaluate(action.number) + action.time_it_takes):
list_for_check[index] = 1
But I get the error:
'IntNumRef' object cannot be interpreted as an integer
I've understood that Z3 isn't returning normal ints or bools in their models, but writing
if m.evaluate(action.boolean):
works, so I'm assuming the if is overwritten in a way, but this doesn't seem to be the case with range. So my question is: Is there a way to use range with Z3 ints? Or is there another way to do this?
The problem might also be that action.time_it_takes is an integer and adding a Z3int with a "normal" int doesn't work. (Done in the second part of the range).
I've also tried using int(m.evaluate(action.number)), but it doesn't work.
Thanks in advance :)
When you call evaluate it returns an IntNumRef, which is an internal z3 representation of an integer number inside z3. You need to call as_long() method of it to convert it to a Python number. Here's an example:
from z3 import *
s = Solver()
a = Int('a')
s.add(a > 4);
s.add(a < 7);
if s.check() == sat:
m = s.model()
print("a is %s" % m.evaluate(a))
print("Iterating from a to a+5:")
av = m.evaluate(a).as_long()
for index in range(av, av + 5):
print(index)
When I run this, I get:
a is 5
Iterating from a to a+5:
5
6
7
8
9
which is exactly what you're trying to achieve.
The method as_long() is defined here. Note that there are similar conversion functions from bit-vectors and rationals as well. You can search the z3py api using the interface at: https://z3prover.github.io/api/html/namespacez3py.html
I am trying to use enum in golang as below. I am struggling to find a easy way to iterate over the list of constant values. What are common practice in golang to iterate over constant values used as enum. Thanks!
type DayOfWeek int
const(
Monday DayOfWeek = iota
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
)
In Java, we can iterate as below.
public enum DayOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
for (DayOfWeek day: DayOfWeek.values()) {
// code logic
}
There is no direct way to enumerate the values/instances of named type at runtime, whether variables or constants, unless you specifically define a slice that lists them. This is left up to the definer or the user of the enumeration type.
package main
import (
"fmt"
"time"
)
var Weekdays = []time.Weekday{
time.Sunday,
time.Monday,
time.Tuesday,
time.Wednesday,
time.Thursday,
time.Friday,
time.Saturday,
}
func main() {
for _, day := range Weekdays {
fmt.Println(day)
}
}
In order be able to generate this list dynamically at runtime, e.g. via reflection, the linker would have to retain all the symbols defined in all packages, like Java does. The golang-nuts group discussed this, regarding names and functions exported from a package, a superset of package constant definitions. https://groups.google.com/forum/#!topic/golang-nuts/M0ORoEU115o
It would be possible for the language to include syntactic sugar for generating this list at compile time if and only if it were referenced by the program. What should the iteration order be, though? If your week starts on Monday the list I defined is not very helpful; you will have to define your own slice to range through the days from Monday to Sunday.
You can do that without reflection.
First execute the Go tools Stringer at compile time using go generate. This creates a file [filename]_string.go which contains a map _[structname]_map of enum values referencing enum variable names as strings. This map is private, so simply assign it to a public map upon package initialization.
var EnumMap map[Enum]string
func init() {
EnumMap = _Enum_map
}
type Enum uint
//go:generate go run golang.org/x/tools/cmd/stringer -type=Enum
const (
One Enum = iota
Two
)
Then you can simply loop over the keys of the map.
The comment from #davec was great. This works perfect when you have a count that increments by one.
You could either do a simple loop such as for d := Monday; d <= Sunday; d++ {}
I had constant that jumped in bits (1,2,4,8,16 etc):
const (
Approved = 1 << iota
AlreadyApproved
NotApproved
OldTicket
Unknown
)
I avoided range and did a left shift one to move through my constant:
var score Bits
score = Set(score, AlreadyApproved)
for i := Approved; i < Unknown; i = i << 1 {
fmt.Println(i)
}
Output:
1
2
4
8
16
Using stringer is preferable it can help you keep your codebase up to date using code generators. Unfortunately stringer does not always generate the map.
For anyone interested in keep using go generators for this purpose I wrote a small code generator called enumall. It produces a file for each provided type with variable holding all values for given type.
Use it by adding code generator comment to your code like this:
//go:generate go run github.com/tomaspavlic/enumall#latest -type=Season
type Season uint8
const (
Spring Season = 1 << iota
Summer
Autumn
Winter
)
You can find more information here: https://github.com/tomaspavlic/enumall
This question already has answers here:
Passing lists from one function to another in Swift
(2 answers)
Closed 7 years ago.
I am getting a Binary operator '/' cannot be applied to two (Int) operands error when I put the following code in a Swift playground in Xcode.
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
The above was a function calculating the total sum of any numbers.
Below is a function calculating the average of the numbers. The function is calling the sumOf() function from within itself.
func avg(numbers: Int...) -> Float {
var avg:Float = ( sumOf(numbers) ) / ( numbers.count ) //Binary operator '/' cannot be applied to two (Int) operands
return avg
}
avg(1, 2, 3);
Note: I have looked everywhere in stack exchange for the answer, but the questions all are different from mine because mine is involving two Ints, the same type and not different two different types.
I would like it if someone could help me to solve the problem which I have.
Despite the error message it seems that you cannot forward the sequence (...) operator. A single call of sumOf(numbers) within the agv() function gives an error cannot invoke sumOf with an argument of type ((Int))
The error is telling you what to do. If you refer to https://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_operators.html
/ Division.
A binary arithmetic operator that divides the number to its left by the number to its right.
Class of operands: integer, real
Class of result: real
The second argument has to be real. Convert it like so. I don't use xcode, but I think my syntax is correct.
var avg:Float = ( sumOf(numbers) ) / Float( numbers.count )
I have following problem with my function which should return a random numer. When I want to generate a couple of numbers by calling that function, they are exactly the same. How can I fix the problem of returning the same number all the time when I call the function? I need that random to keep in function.
Here is the code:
with Ada.Numerics.discrete_Random
function generate_random_number ( n: in Positive) return Integer is
subtype Rand_Range is Integer range 0 .. n;
package Rand_Int is new Ada.Numerics.Discrete_Random(Rand_Range);
use Rand_Int;
gen : Rand_Int.Generator;
ret_val: Rand_Range;
begin
Rand_Int.Reset(gen);
ret_val := Random(gen);
return ret_val;
end;
The random generator gen should not be local to the function. Currently you are creating it anew on each generate_random_number call, and initialising it, so it's not surprising you always get the same result.
If you make gen - for instance - a global variable, initialised once, then each time you use it you'll get a new random number. (Yes, global variables are bad : but see below)
Unfortunately this does not play particularly well with the semantics of function generate_random_number ( n: in Positive) which can restrict the range of the random number differently each time. The simplest solution is to make gen return any valid integer and use modular arithmetic to return a number in the correct range for each call. This will work but you should be aware that it potentially introduces cryptographic weaknesses, beyond my skills to analyze.
If that is the case you will need a different approach, for example creating a different random generator for each range you need; taking care to seed (reset) them differently otherwise there may again be crypto weaknesses such as correlations between different generators.
Now global variables are poor structure for all the usual reasons in any language. So a much better way is to make it a resource by wrapping it in a package.
package RandGen is
function generate_random_number ( n: in Positive) return Positive;
end RandGen;
And that is all the client needs to see. The package is implemented as follows:
with Ada.Numerics.discrete_Random;
package body RandGen is
subtype Rand_Range is Positive;
package Rand_Int is new Ada.Numerics.Discrete_Random(Rand_Range);
gen : Rand_Int.Generator;
function generate_random_number ( n: in Positive) return Integer is
begin
return Rand_Int.Random(gen) mod n; -- or mod n+1 to include the end value
end generate_random_number;
-- package initialisation part
begin
Rand_Int.Reset(gen);
end RandGen;
EDIT : Jacob's suggestion of rejecting out-of-range values is better but inefficient if n is much smaller than the generator range. One solution might be to create several generators and let the generate_random_number function choose the one which covers 0 .. N with least waste.
The Random procedure with only one parameter is supposed to initiate the random number generator with a "time-dependent state". However, if it is called more than once rapidly in succession, it is very likely that the "time" that the program uses will be the same each time, since the program is likely to run faster than the clock resolution. (Try your test with something like delay 0.5 in between the two uses of generate_random_number; most likely you will get two different results.)
In any event, the intended use of a random number generator is to use Reset on it once to set the seed, and then generate a sequence of random numbers starting with the seed. By doing this, you can also use the same seed every time in order to get a duplicatable sequence of random numbers, for testing; or you can use a time-dependent seed. However, resetting the random number generator every time you want a random number is not the normal or recommended way of using RNG's. Therefore, you need to move the Reset call out of generate_random_number. Unfortunately, this also means that you have to use the same generator even if the n parameter will be different on every call, which means you may be forced to use Float_Random instead of Discrete_Random.
P.S. Looking into it further, I found this in G.2.5: "Two different calls to the time-dependent Reset procedure shall reset the generator to different states, provided that the calls are separated in time by at least one second and not more than fifty years." [Emphasis mine.] I'm sure that when you tried it, the calls were less than one second apart.
Assuming that the upper limit can be determined when you start the program:
Package Random (specification):
with Generic_Random;
with Upper_Limit_Function;
package Random is new Generic_Random (Upper_Limit => Upper_Limit_Function);
Generic package Generic_Random (specification):
generic
Upper_Limit : Positive;
package Generic_Random is
subtype Values is Natural range 0 .. Upper_Limit;
function Value return Values;
end Generic_Random;
Generic package Generic_Random (body):
with Ada.Numerics.Discrete_Random;
package body Generic_Random is
package Random is new Ada.Numerics.Discrete_Random (Values);
Source : Random.Generator;
function Value return Values is
begin
return Random.Random (Source);
end Value;
begin
Random.Reset (Source);
end Generic_Random;
Is there any equivalent in go for the Arduino map function?
map(value, fromLow, fromHigh, toLow, toHigh)
Description
Re-maps a number from one range to another. That is, a value of
fromLow would get mapped to toLow, a value of fromHigh to toHigh,
values in-between to values in-between, etc
If not, how would I implement this in go?
Is there any equivalent in go for the Arduino map function?
The standard library, or more specifically the math package, does not offer such a function, no.
If not, how would I implement this in go?
By taking the original code and translating it to Go. C and Go are very related syntactically and therefore this task is very, very easy. The manual page for map that you linked gives you the code. A translation to go is, as already mentioned, trivial.
Original from the page you linked:
For the mathematically inclined, here's the whole function
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
You would translate that to something like
func Map(x, in_min, in_max, out_min, out_max int64) int64 {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
}
Here is an example on the go playground.
Note that map is not a valid function name in Go since there is already the map built-in type which makes map a reserved keyword. keyword for defining map types, similar to the []T syntax.