How to create an IntStream with custom increments? - iterator

I thought if it was possible to create a stream which has a custom increment, like one only containing multiples of a given number (2 in this example). Is there a way to make this work?
IntStream.iterate(2, num -> (int) Math.pow(2, num))

Multiples of a number? Shouldn't this work?
IntStream.iterate(2, i -> i + 1)
.filter(i -> i % 2 == 0)
.limit(5)
.forEach(System.out::println);

Related

How can we generate random values in Scrypto?

How can we generate random numbers in Scrypto if floating point libraries are not allowed be used? I want to be able to generate unique IDs for NFTs.
There are 2 ways to solve this:
Self managed - if the data structure is a Vec, we can use vec.len() + 1 as the generated ID, making things more trivial.
Generated Uuid - Scrypto provides Runtime::generate_uuid which is a generated number format in Uuid which should guarantee uniqueness
We can also generate values given a max range:
fn get_random(end: usize) -> usize {
let num = Runtime::generate_uuid();
(num % end as u128) as usize
}
// prints number between 0 - 5
info!("{}", get_random(5));
You can generate a pseudo random NFT id using the built-in NonFungibleId::random() method.
let new_nft_id: NonFungibleId = NonFungibleId::random();
Reference: https://radixdlt.github.io/radixdlt-scrypto/scrypto/resource/struct.NonFungibleId.html

How to match on all integers in a range in a total function?

Let's say we want to check the parity of an Int:
data Parity = Even | Odd
It would be pretty easy for Nat:
parity0: Nat -> Parity
parity0 Z = Even
parity0 (S k) = case parity0 k of
Even => Odd
Odd => Even
The first attempt to implement that for Int:
parity1: Int -> Parity
parity1 x = if mod x 2 == 0 then Even else Odd
This function is not total:
Main.parity1 is possibly not total due to: Prelude.Interfaces.Int implementation of Prelude.Interfaces.Integral
It makes sense because mod is not total for Int. (Although I'm not sure how I could know it in advance. The REPL shows that mod is total. Apparently, you can use a partial function to implement a total function of an interface? Strange.)
Next, I try to use DivBy view:
parity2: Int -> Parity
parity2 x with (divides x 2)
parity2 ((2 * div) + rem) | (DivBy prf) =
if rem == 0 then Even else Odd
This function works and is total, but the implementation is error-prone and doesn't scale to cases where we have multiple possible values. I'd like to assert that rem can only be 0 or 1. So I attempt to use case on rem:
parity3: Int -> Parity
parity3 x with (divides x 2)
parity3 ((2 * div) + rem) | (DivBy prf) = case rem of
0 => Even
1 => Odd
This function also works but is not total. How can I use prf provided by DivBy to convince the compiler that it's total? How can I use this prf in general?
Would using Integer or some other type make this problem easier to solve?
And there is another very concerning thing. I tried to case-split on prf and discovered that the following function is total:
parity4: Int -> Parity
parity4 x with (divides x 2)
parity4 ((2 * div) + rem) | (DivBy prf) impossible
Is that a bug? I can use this function to produce a runtime crash in a program that only contains total functions.

How to sum integers from 1 to n

I must sum of the even integers between 1 and ' n ' (inclusive). For example for n = 5 program return 6(2+4). How to make it?
a = 0
for (i in n):
if (i.IsEven()):
a += i
return a
or something like that, also you can substitute iseven() for something simple like checking i%2 ==0
1..5 |> Enum.filter(&(rem(&1, 2) == 0)) |> Enum.sum
(In elixir. You didn't say which language.)

Max number of consecutive values (Minizinc)

I'm trying to model the next constraint in Minizinc:
Suppose S is an array of decision variables of size n. I want my decision variables to take a value between 1-k, but there is a maximum 'Cons_Max' on the number of consecutive values used.
For example, suppose Cons_Max = 2, n = 8 and k = 15, then the sequence [1,2,4,5,7,8,10,11] is a valid sequence , while e.g. [1,2,3,5,6,8,9,11] is not a valid sequence because the max number of consecutive values is equal to 3 here (1,2,3).
Important to mention is that sequence [1,3,5,7,9,10,12,14] is also valid, because the values don't need to be consecutive but the max number of consectuive values is fixed to 'Cons_Max'.
Any recommendations on how to model this in Minizinc?
Here's a model with a approach that seems to work. I also added the two constraints all_different and increasing since they are probably assumed in the problem.
include "globals.mzn";
int: n = 8;
int: k = 15;
int: Cons_Max = 2;
% decision variables
array[1..n] of var 1..k: x;
constraint
forall(i in 1..n-Cons_Max) (
x[i+Cons_Max]-x[i] > Cons_Max
)
;
constraint
increasing(x) /\
all_different(x)
;
%% test cases
% constraint
% % x = [1,2,4,5,7,8,10,11] % valid solution
% % x = [1,3,5,7,9,10,12,14] % valid valid solution
% % x = [1,2,3,5,6,8,9,11] % -> not valid solution (-> UNSAT)
% ;
solve satisfy;
output ["x: \(x)\n" ];
Suppose you use array x to represent your decision variable.
array[1..n] of var 1..k: x;
then you can model the constraint like this.
constraint not exists (i in 1..n-1)(
forall(j in i+1..min(n, i+Cons_Max))
(x[j]=x[i]+1)
);

Objective C - Random results is either 1 or -1

I am trying randomly generate a positive or negative number and rather then worry about the bigger range I am hoping to randomly generate either 1 or -1 to just multiply by my other random number.
I know this can be done with a longer rule of generating 0 or 1 and then checking return and using that to either multiply by 1 or -1.
Hoping someone knows of an easier way to just randomly set the sign on a number. Trying to keep my code as clean as possible.
I like to use arc4random() because it doesn't require you to seed the random number generator. It also conveniently returns a uint_32_t, so you don't have to worry about the result being between 0 and 1, etc. It'll just give you a random integer.
int myRandom() {
return (arc4random() % 2 ? 1 : -1);
}
If I understand the question correctly, you want a pseudorandom sequence of 1 and -1:
int f(void)
{
return random() & 1 ? 1 : -1;
// or...
// return 2 * (random() & 1) - 1;
// or...
// return ((random() & 1) << 1) - 1;
// or...
// return (random() & 2) - 1; // This one from Chris Lutz
}
Update: Ok, something has been bothering me since I wrote this. One of the frequent weaknesses of common RNGs is that the low order bits can go through short cycles. It's probably best to test a higher-order bit: random() & 0x80000 ? 1 : -1
To generate either 1 or -1 directly, you could do:
int PlusOrMinusOne() {
return (rand() % 2) * 2 - 1
}
But why are you worried about the broader range?
return ( ((arc4random() & 2) * 2) - 1 );
This extra step won't give you any additional "randomness". Just generate your number straight away in the range that you need (e.g. -10..10).
Standard rand() will return a value from this range: 0..1
You can multiply it by a constant to increase the span of the range or you can add a constant to push it left/right on the X-Axis.
E.g. to generate random values from from (-5..10) range you will have:
rand()*15-5
rand will give you a number from 0 to RAND_MAX which will cover every bit in an int except for the sign. By shifting that result left 1 bit you turn the signed MSB into the sign, but have zeroed-out the 0th bit, which you can repopulate with a random bit from another call to rand. The code will look something like:
int my_rand()
{
return (rand() << 1) + (rand() & 1);
}