Set of bytes, what are the values of a and b - pascal

program Project1;
var
a,b:set of byte;
c:set of byte;
i:integer;
begin
a:=[3];
b:=[2];
c:=(a+b)*(a-b);
FOR i:= 0 TO 5 DO
IF i IN c THEN write(i:2);
readln;
end.
Can someone please explain to me what is going on in this code. I know that c=3 but dont understand how, what are the values of a and b ? Tried writeln(a,b); but gives me an error ...

Ok, I'll explain what you probably could find out by debugging, or by simply reading a textbook on Pascal as well:
The line:
c := (a+b)*(a-b);
does the following:
a + b is the union of the two sets, i.e. all elements that are
in a or in b or in both, so here, that is [2, 3];
a - b is the difference of the two sets, i.e. it is a minus the
elements of a that happen to be in b too. In this case, no
common elements to be removed, so the result is the same as a,
i.e. [3]
x * y is the intersection of the two sets, i.e. elements that are in
x as well as in y (i.e. a set with the elements both have in common).
Say, x := a + b; y := a - b;, then it can be disected as:
x := a + b; // [3] + [2] --> [2, 3]
y := a - b; // [3] - [2] --> [3]
c := x * y; // [2, 3] * [3] --> [3]

Related

Slice can access another slice out of range but indexing out of range causes panic

My code:
package main
import (
"fmt"
)
func main() {
a := [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
b := a[1:4]
fmt.Println("a:", a)
fmt.Println("b:", b)
// Works fine even though c is indexing past the end of b.
c := b[4:7]
fmt.Println("c:", c)
// This fails with panic: runtime error: index out of range [4] with length 3
// d := b[4]
}
Output:
a: [0 1 2 3 4 5 6 7 8 9]
b: [1 2 3]
c: [5 6 7]
If I uncomment the line that contains d := b[4], it leads to this this error:
panic: runtime error: index out of range [4] with length 3
My question:
Why is it okay to access b[4:7] even though the index 4 is out of range for b which has a length 3 but it is not okay to access b[4]? What Go language rules explain this behavior?
Relevant rules: Spec: Index expressions and Spec: Slice expressions.
In short: when indexing, index must be less than the length. When slicing, upper index must be less than or equal to the capacity.
When indexing: a[x]
the index x is in range if 0 <= x < len(a), otherwise it is out of range
When slicing: a[low: high]
For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length.
When you do this:
b := a[1:4]
b will be a slice sharing the backing array with a, b's length will be 3 and its capacity will be 9. So later it is perfectly valid to slice b even beyond its length, up to its capacity which is 9. But when indexing, you can always index only the part covered by the slice's length.
We use indexing to access current elements of a slice or array, and we use slicing if we want to create a fragment of an array or slice, or if we want to extend it. Extending it means we want a bigger portion (but what is still covered by the backing array).

Golang struct gets different value from input

I am seeing weird behavior in the following code:
type A struct {
D []int8
}
func main() {
a := A{D: make([]int8, 0)}
a.D = append(a.D, 0)
b := a
c := a
b.D = append(b.D, 1)
c.D = append(c.D, 2)
fmt.Println(a.D, b.D, c.D)
}
I'm expecting output to be
[0] [0 1] [0 2]
However I got
[0] [0 2] [0 2]
Anyone know why...?
p.s. If I comment out line "a.D = append(a.D, 0)", or change the type of D from "[ ]int8" to "[ ]int", I got what I expected. Weird...
First off, changing the type doesn't fix it: https://play.golang.org/p/fHX3JAtfNz
What is happening here has to do with the mechanics of append and reference types.
Basically, all three structs are pointing at the same underlying array, but each slice has its own unique length argument.
So when you append 1 to b, it is [0 1] with a length of 2. c is still [0] with a length of 1. You then append 2 to c, making it [0 2] with a length of 2. Inadvertently, you are also changing the second value of the array in b. If you could change the length of the a without append, it would also be [0 2].
Make sense? Pointers and slices are weird. Full story is here: https://blog.golang.org/slices

Algorithm to find closest integer values that meet certain criteria

Edited to clarify the application by adding units (ml) and explaining the difficulty to measure wet reagents by units of 1/26. The word 'solution' was ambiguous because it was used to mean both a chemical solution as well as the solution to the problem.
Added results based on Edward's reply
The real world application is that I am trying to determine the closest "convenient" volumes to use when mixing reagents A and B to create a solution (in the wet chemistry sense) that best approximates a specific A:B ratio. Let's define "convenient" as divisible by 5.
Example
Given:
1. X = A/(A+B) * C
2. Y = B/(A+B) * C
3. X + Y = C
4. A, B, C always positive integer
// e.g. a 500ml solution (wet chemistry sense) C with a 1:25 ratio of A and B
A = 1
B = 25
C = 500
This gives the volumes to use of X and Y to create the solution (wet chemistry sense) with the proper A:B ratio.
X = 500/26 = ~19.23ml
Y = 12500/26 = ~480.77ml
C = 13000/26 = 500ml
These are the exact volumes create a total volume of 500ml, but trying to measure reagent volumes in units of 1/26ml is a challenge.
How to find "convenient values" (integer divisible by 5) for X, Y, and C that best approximate the exact values of X, Y, and C that would be multiples of 1/26? In this case I found as the closest "convenient" values for X, Y, C:
X = 20ml
Y = 500ml
C = 520ml
C in this case (520ml) is more than the required volume of 500ml, but it is more practical to physically measure the volumes of 20mL and 500mL than it would be to measure reagent volumes in 1/26ths. The extra 20mL is discarded, the cost for using nice values.
RESULTS BASED ON EDWARD'S ANSWER
A=1 B=25 C=500
X=20 Y=500 C2=520
A=1 B=20 C=500
X=25 Y=500 C2=525
A=1 B=100 C=500
X=5 Y=500 C2=505
A=1 B=75 C=500
X=10 Y=750 C2=760
A=1 B=50 C=900
X=20 Y=1000 C2=1020
One way to approach this would be to adjust C so that it absorbs the factor A+B. Then the ratio of A to B would be exact, and X, Y, and C would all be integers. Let D = 5*(A+B), C2 = ceiling(C/((double)D)) * D (round up so you get enough C), X = C2/(A+B)*A, Y = C2/(A+B)*B. If you want the closest value of C, use C2 = round(C/((double)D))*D instead.
If you're mixing chemicals, you probably want to round up rather than round to closest so you'll have enough with a little waste left over, which is better than not having enough.
You can phrase this as an optimization problem with an L1 (absolute value) objective function. (This is using a cannon to swat a mosquito, but I did it because I wanted to figure out about the L1 optimization.) I used the program glpsol from the GLPK package (open source). Here is my program:
param A, integer, >= 0;
param B, integer, >= 0;
param C, integer, >= 0;
var x, integer, >= 0;
var y, integer, >= 0;
var e1x, >= 0;
var e1y, >= 0;
minimize e1 : e1x + e1y;
subject to
c1 : (5*x - (C*A)/(A + B)) <= e1x;
c2 : ((C*A)/(A + B) - 5*x) <= e1x;
c3 : (5*y - (C*B)/(A + B)) <= e1y;
c4 : ((C*B)/(A + B) - 5*y) <= e1y;
solve;
printf "x=%g, y=%g, error=%g\n", x, y, e1;
data;
param A := 1;
param B := 25;
param C := 500;
Here is the output:
$ glpsol --model find_nice_integers.mod
[... snip ...]
x=4, y=96, error=1.53846
Here are some notes about how to handle absolute values in optimization problems.
So, you are given an integer number C and the ratio p:q between two other integer numbers A and B (i.e., A/B = p/q).
I will interpret your definition of convenient as requiring that X and Y are both multiple of 5 where
X = A / (A+B) * C'
Y = B / (A+B) * C'
C' is close to C
Replacing A/B with p/q we get
X = p / (p+q) * C'
Y = q / (p+q) * C'
Now, in order for X and Y to be integer both p * C' and q * C' must both be multiples of (p+q). And since we can assume that p:q is irreductible (i.e., p and q have no multiples in common) this means that C' must be divisible by p+q. In addition, C'/(p+q) must be multiple of 5. So, C' must be a multiple of 5*(p+q).
The multiple of 5*(p+q) that is closest to C is:
C' := round(C/(5*(p+q)))*5*(p+q)
Now we can calculate:
X := p/(p+q)*C'
Y := q/(p+q)*C'
and they are indeed multiple of 5 because C'/(p+q) is.
Let's see how this behaves with your example:
Inputs:
p = 1
q = 25
C = 500
Then
C' := round(500/5(1+25))*5*(1+25) = round(100/26)*5*26 = 4*5*26 = 520
Hence
X := p/(p+q)*C' = 1/(1+25)*4*5*26 = 1/26*4*5*26 = 4*5 = 20
Y := q/(p+q)*C' = 25/(1+25)*4*5*26 = 25/26*4*5*26 = 25*4*5 = 500.
Voila!
Let's first calculate optimal(float) A and B.
It could be Observed that optimal integer solutions are either {floor(A), ceiling(B)} or {ceiling(A), floor(B)}. So we simply try both and chose the answer with less error.

Counting bits in an array

Given that we know how many bits are set in N elements that is if say we have array A and array of array B .
A store element
B[i] store positions of bits set corresponding to A[i].
Then question is can we find how many bits are set in sum of all A[i] for 1<=i<=N using this B array.
Like say we have A=[700,40]
As 700 is 1010111100 so we have [2 3 4 5 7 9]
As 40 is 101000 so we have [3 5]
B is [[2,3,4,5,7,9],[3,5]]
And we want count of bits set in 740.
How this can be done in efficient way ? Please help
This is about binary addition. In your example
A[0] = 1010111100 B[0] = [2,3,4,5,7,9]
A[1] = 0000101000 B[1] = [3,5]
A[0]+A[1] = 1011100100
So the sum is represented as [2,5,6,7,9]. Can you see how to get to this array given B[0] and B[1]?
Here's how you can proceed with just two arrays:
set B = B[0]
while B[1] not empty:
for each b in B[1]:
if b not in B:
append b to B
remove b from B[1]
else:
remove b from B
increment each of the remaining elements in B[1] by 1
return length(B)
You have to mimic binary addition via the elements of the B arrays.
To get the number of bits set, you just return the number of elements in B.
So given the array B, you want to calculate the sum of the elements of A, 740 in this example?
Easy:
int sum = 0;
foreach( var bSubArray in B)
foreach( var b in bSubArray)
sum += Power( 2, b);

Pseudo number generation

Following is text from Data structure and algorithm analysis by Mark Allen Wessis.
Following x(i+1) should be read as x subscript of i+1, and x(i) should be
read as x subscript i.
x(i + 1) = (a*x(i))mod m.
It is also common to return a random real number in the open interval
(0, 1) (0 and 1 are not possible values); this can be done by
dividing by m. From this, a random number in any closed interval [a,
b] can be computed by normalizing.
The problem with this routine is that the multiplication could
overflow; although this is not an error, it affects the result and
thus the pseudo-randomness. Schrage gave a procedure in which all of
the calculations can be done on a 32-bit machine without overflow. We
compute the quotient and remainder of m/a and define these as q and
r, respectively.
In our case for M=2,147,483,647 A =48,271, q = 127,773, r = 2,836, and r < q.
We have
x(i + 1) = (a*x(i))mod m.---------------------------> Eq 1.
= ax(i) - m (floorof(ax(i)/m)).------------> Eq 2
Also author is mentioning about:
x(i) = q(floor of(x(i)/q)) + (x(i) mod Q).--->Eq 3
My question
what does author mean by random number is computed by normalizing?
How author came with Eq 2 from Eq 1?
How author came with Eq 3?
Normalizing means if you have X ∈ [0,1] and you need to get Y ∈ [a, b] you can compute
Y = a + X * (b - a)
EDIT:
2. Let's suppose
a = 3, x = 5, m = 9
Then we have
where [ax/m] means an integer part.
So we have 15 = [ax/m]*m + 6
We need to get 6. 15 - [ax/m]*m = 6 => ax - [ax/m]*m = 6 => x(i+1) = ax(i) - [ax(i)/m]*m
If you have a random number in the range [0,1], you can get a number in the range [2,5] (for example) by multiplying by 3 and adding 2.

Resources