Transposing the key using jfugue - Some questions concerning Jfugue - jfugue

I have a couple of questions concerning JFugue (5, the beta version).
From The complete guide to JFugue, it is mentioned that depending on the Key Signature in the pattern, JFugue interprets the note value. As an example, in the case of an F-major key, B would be automatically translated to B-flat, unless we write "Bn" instead.
The question is that if we are dealing with an F major key and write "Bb" how would JFugue interpret it ? As "Bbb" or as a "Bb" note ?
My second question is about transposing Keys in JFugue. What is the fastest way of doing so ?
Thank you for your help,
Best Regards,
Hussein Hammoud.

Answer to the first part of your question: In the key of F-Major, Bb is played like Bb, the same as B itself when played in F-Major. Here's a program that tests this:
StaccatoParser parser = new StaccatoParser();
DiagnosticParserListener dpl = new DiagnosticParserListener();
parser.addParserListener(dpl);
Pattern pattern = new Pattern("KEY:Cmaj B Bn Bb KEY:FMaj B Bn Bb");
parser.parse(pattern);
And its output (note that MIDI Note 70 is Bb and MIDI Note 71 is B):
Before parsing starts
Key signature parsed: key = 0 scale = 1
Note parsed: value = 71 duration = 0.25 onVelocity = 64 offVelocity = 64
Note parsed: value = 71 duration = 0.25 onVelocity = 64 offVelocity = 64
Note parsed: value = 70 duration = 0.25 onVelocity = 64 offVelocity = 64
Key signature parsed: key = 5 scale = 1
Note parsed: value = 70 duration = 0.25 onVelocity = 64 offVelocity = 64
Note parsed: value = 71 duration = 0.25 onVelocity = 64 offVelocity = 64
Note parsed: value = 70 duration = 0.25 onVelocity = 64 offVelocity = 64
After parsing finished
Answer to the second part of your question: I'm not sure there's a decent answer right now. But you have inspired me to write a transpose() method on the Pattern class. Thank you!

Related

Finding the formula for an alphanumeric code

A script I am making scans a 5-character code and assigns it a number based on the contents of characters within the code. The code is a randomly-generated number/letter combination. For example 7D3B5 or HH42B where any position can be any one of (26 + 10) characters.
Now, the issue I am having is I would like to figure out the number from 1-(36^5) based on the code. For example:
00000 = 0
00001 = 1
00002 = 2
0000A = 10
0000B = 11
0000Z = 36
00010 = 37
00011 = 38
So on and so forth until the final possible code which is:
ZZZZZ = 60466176 (36^5)
What I need to work out is a formula to figure out, let's say G47DU in its number form, using the examples below.
Something like this?
function getCount(s){
if (!isNaN(s))
return Number(s);
return s.charCodeAt(0) - 55;
}
function f(str){
let result = 0;
for (let i=0; i<str.length; i++)
result += Math.pow(36, str.length - i - 1) * getCount(str[i]);
return result;
}
var strs = [
'00000',
'00001',
'00002',
'0000A',
'0000B',
'0000Z',
'00010',
'00011',
'ZZZZZ'
];
for (str of strs)
console.log(str, f(str));
You are trying to create a base 36 numeric system. Since there are 5 'digits' each digit being 0 to Z, the value can go from 0 to 36^5. (If we are comparing this with hexadecimal system, in hexadecimal each 'digit' goes from 0 to F). Now to convert this to decimal, you could try use the same method used to convert from hex or binary etc... system to the decimal system.
It will be something like d4 * (36 ^ 4) + d3 * (36 ^ 3) + d2 * (36 ^ 2) + d1 * (36 ^ 1) + d0 * (36 ^ 0)
Note: Here 36 is the total number of symbols.
d0, d1, d2, d3, d4 can range from 0 to 35 in decimal (Important: Not 0 to 36).
Also, you can extend this for any number of digits or symbols and you can implement operations like addition, subtraction etc in this system itself as well. (It will be fun to implement that. :) ) But it will be easier to convert it to decimal do the operations and convert it back though.

Why am I getting negative integer after adding two positive 16 bit integers?

I am a newbie to golang, actually, I am new to type based programming. I have only knowledge of JS.
While going through simple examples in golang tutorials. I found that adding a1 + a2 provides a negative integer value?
var a1 int16 = 127
var a2 int16 = 32767
var rr int16 = a1 + a2
fmt.Println(rr)
Result:
-32642
Excepted:
The compiler will throw an error as a exceeded the int16 max.
( OR ) GO automatically convert the int16 to int32.
32,894
Can you guys explain why it is showing -32642.
This is the result of Integer Overflow behaving as defined in the specification.
You don't see your expected results, because
Overflow happens at runtime, not compile time.
Go is statically typed.
32,894 is greater than the max value representable by an int16.
It’s very simple.
The 16 bit integer maps the positive part I 0 - 32767 (0x0000, 0x7FFF) and the negative part from 0x8000 (−32768) to 0xFFFF (-1).
For example 0 - 1 = -1 and it’s store as 0xFFFF.
Now in your specific case: 32767 + 127.
You overflow because 32767 is the max value for a signed 16 bit integer, but, if you force the addition 0x7FFF + 7F = 807E and convert 807E to signed 16 bit integer you obtain -32642.
You can better understand here: Signed number representations
Aditionally, check these Math Constants:
const (
MaxInt8 = 1<<7 - 1
MinInt8 = -1 << 7
MaxInt16 = 1<<15 - 1
MinInt16 = -1 << 15
MaxInt32 = 1<<31 - 1
MinInt32 = -1 << 31
MaxInt64 = 1<<63 - 1
MinInt64 = -1 << 63
MaxUint8 = 1<<8 - 1
MaxUint16 = 1<<16 - 1
MaxUint32 = 1<<32 - 1
MaxUint64 = 1<<64 - 1
)
And check the human version of these values here

Retrieving a descriptive value for WMI Win32_Processor.Family property instead of an index

The below simple VBS example retrieves CPU caption, architecture and family from WMI:
s = ""
For Each Item In GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\Root\CIMV2").InstancesOf("Win32_Processor")
s = s & "Caption = " & Item.Caption & vbCrLf
s = s & "Architecture = " & Item.Architecture & vbCrLf
s = s & "Family = " & Item.Family & vbCrLf
Next
WScript.Echo s
The output for me is:
Caption = Intel64 Family 6 Model 42 Stepping 7
Architecture = 9
Family = 198
What I want is to retrieve more descriptive values for architecture and family instead of indexes. Such properties have Values qualifier, which specifies a list of possible values for the property, and ValueMap qualifier, which specifies the integer values of the corresponding string values in Values. That qualifiers are shown on the screenshots I made of two utilities:
WMI Code Creator
WMI CIM Studio
On the last screenshot you can see Win32_Processor class, Architecture propertry, Values qualifier, that contains the array of six strings: x86, MIPS, Alpha, PowerPC, ia64, x64 which corresponds the indexes from array in ValueMap qualifier: 0, 1, 2, 3, 6, 9. However the below code doesn't enumerate the qualifiers marked as amended in WMI CIM Studio, such as Description and Values for unknown reason:
Set objClass = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\CIMV2:Win32_Processor")
s = ""
For Each objQualifier In objClass.Properties_("Architecture").Qualifiers_
s = s & objQualifier.Name & " = "
If IsArray(objQualifier.Value) Then
s = s & "{" & Join(objQualifier.Value, ", ") & "}"
Else
s = s & objQualifier.Value
End If
s = s & vbCrLf
Next
WScript.Echo s
I tried to run it on x64 and x86 hosts, and it returns the same output, as follows:
CIMTYPE = uint16
MappingStrings = {WMI}
read = True
ValueMap = {0, 1, 2, 3, 6, 9}
While I expected:
CIMTYPE = uint16
Description = The Architecture property specifies the processor architecture used by this platform. It returns one of the following integer values:
0 - x86
1 - MIPS
2 - Alpha
3 - PowerPC
6 - ia64
9 - x64
MappingStrings = {WMI}
read = True
ValueMap = {0, 1, 2, 3, 6, 9}
Values = {x86, MIPS, Alpha, PowerPC, ia64, x64}
How can I get that qualifiers? Is there any other way to retrieve them?
UPDATE
I've managed to get all property qualifiers, including amended, thanks to #Kul-Tigin for pointing me in the right direction and providing links. Having access to the qualifiers, I extract Values and ValueMap arrays from class and create a sort of conversion table oMap intended for an integer property value translation into an associated string:
Const wbemFlagUseAmendedQualifiers = 131072
Set oService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\Root\CIMV2")
s = ""
For Each oInstance In oService.InstancesOf("Win32_Processor")
For Each sName In Array("Caption", "Family")
s = s & sName & " = " & oInstance.Properties_.Item(sName).Value & vbCrLf
Next
Next
s = s & vbCrLf
Set oClass = oService.Get("Win32_Processor", wbemFlagUseAmendedQualifiers)
Set oProperty = oClass.Properties_.Item("Family")
aValues = oProperty.Qualifiers_.Item("Values")
aValueMap = oProperty.Qualifiers_.Item("ValueMap")
Set oMap = CreateObject("Scripting.Dictionary")
For i = 0 To UBound(aValues)
oMap(aValueMap(i)) = aValues(i)
Next
For Each sKey In oMap
s = s & sKey & " = " & oMap(sKey) & vbCrLf
Next
WScript.Echo s
The output for me is as follows:
Caption = Intel64 Family 6 Model 42 Stepping 7
Family = 198
1 = Other
2 = Unknown
3 = 8086
4 = 80286
5 = 80386
6 = 80486
7 = 8087
8 = 80287
9 = 80387
10 = 80487
11 = Pentium(R) brand
12 = Pentium(R) Pro
13 = Pentium(R) II
14 = Pentium(R) processor with MMX(TM) technology
15 = Celeron(TM)
16 = Pentium(R) II Xeon(TM)
17 = Pentium(R) III
18 = M1 Family
19 = M2 Family
24 = K5 Family
25 = K6 Family
26 = K6-2
27 = K6-3
28 = AMD Athlon(TM) Processor Family
29 = AMD(R) Duron(TM) Processor
30 = AMD29000 Family
31 = K6-2+
32 = Power PC Family
33 = Power PC 601
34 = Power PC 603
35 = Power PC 603+
36 = Power PC 604
37 = Power PC 620
38 = Power PC X704
39 = Power PC 750
48 = Alpha Family
49 = Alpha 21064
50 = Alpha 21066
51 = Alpha 21164
52 = Alpha 21164PC
53 = Alpha 21164a
54 = Alpha 21264
55 = Alpha 21364
64 = MIPS Family
65 = MIPS R4000
66 = MIPS R4200
67 = MIPS R4400
68 = MIPS R4600
69 = MIPS R10000
80 = SPARC Family
81 = SuperSPARC
82 = microSPARC II
83 = microSPARC IIep
84 = UltraSPARC
85 = UltraSPARC II
86 = UltraSPARC IIi
87 = UltraSPARC III
88 = UltraSPARC IIIi
96 = 68040
97 = 68xxx Family
98 = 68000
99 = 68010
100 = 68020
101 = 68030
112 = Hobbit Family
120 = Crusoe(TM) TM5000 Family
121 = Crusoe(TM) TM3000 Family
122 = Efficeon(TM) TM8000 Family
128 = Weitek
130 = Itanium(TM) Processor
131 = AMD Athlon(TM) 64 Processor Family
132 = AMD Opteron(TM) Family
144 = PA-RISC Family
145 = PA-RISC 8500
146 = PA-RISC 8000
147 = PA-RISC 7300LC
148 = PA-RISC 7200
149 = PA-RISC 7100LC
150 = PA-RISC 7100
160 = V30 Family
176 = Pentium(R) III Xeon(TM)
177 = Pentium(R) III Processor with Intel(R) SpeedStep(TM) Technology
178 = Pentium(R) 4
179 = Intel(R) Xeon(TM)
180 = AS400 Family
181 = Intel(R) Xeon(TM) processor MP
182 = AMD AthlonXP(TM) Family
183 = AMD AthlonMP(TM) Family
184 = Intel(R) Itanium(R) 2
185 = Intel Pentium M Processor
190 = K7
200 = IBM390 Family
201 = G4
202 = G5
203 = G6
204 = z/Architecture base
250 = i860
251 = i960
260 = SH-3
261 = SH-4
280 = ARM
281 = StrongARM
300 = 6x86
301 = MediaGX
302 = MII
320 = WinChip
350 = DSP
500 = Video Processor
I tried the code on another PC also:
Caption = AMD64 Family 21 Model 56 Stepping 1
Family = 72
...
There are few details on MSDN about Standard Qualifiers usage:
ValueMap
This qualifier can be used alone or in combination with the Values qualifier. When used in combination with the Values qualifier, the location of the value in the ValueMap array provides the location of the corresponding entry in the Values array. Use the ValueMap qualifier only with string and integer values. The syntax for representing an integer value in the value map array is [+|=]digit[*digit]. The content, maximum number of digits, and represented value are constrained by the type of the associated property. For example, uint8 may not be signed, must be less than four digits, and must represent a value less than 256.
Values
This property also specifies an array of string values to be mapped to an enumeration property. This qualifier can be applied to either an integer property or a string property, and the mapping can be implicit or explicit. If the mapping is implicit, integer or string property values represent ordinal positions in the Values array. If the mapping is explicit, the property must be an integer, and valid property values are listed in the array defined by the ValueMap qualifier. For more information, see Value Map.
If a ValueMap qualifier is not present, the Values array is indexed (zero-relative) by using the value in the associated property, method return type, or method parameter. If a ValueMap qualifier is present, the values index is defined by the location of the property value in the value map.
Now I'm stuck in retrieving the appropriate string, since there is no such index neither 198 nor 72 in ValueMap qualifier.
The answer is, Values/ValueMap qualifier string table is incomplete and can't be used. You must create such table yourself if you want to map every index into the string value.
The value of Family property of Win32_Processor class comes from Processor Information SMBIOS structure. Values are defined by specification (latest document as of Jan 2018), the table on 46th page contains needed strings:
198 - Intel® Core™ i7 processor
72 - AMD A-Series Processor
Using this data you can create string table and maintain it as new processor types will by introduced in new SMBIOS versions.
Similar data in the form of C++ enum can be found here.

Checking for termination when converting real to rational

Recently I found this in some code I wrote a few years ago. It was used to rationalize a real value (within a tolerance) by determining a suitable denominator and then checking if the difference between the original real and the rational was small enough.
Edit to clarify : I actually don't want to convert all real values. For instance I could choose a max denominator of 14, and a real value that equals 7/15 would stay as-is. It's not as clear that as it's an outside variable in the algorithms I wrote here.
The algorithm to get the denominator was this (pseudocode):
denominator(x)
frac = fractional part of x
recip = 1/frac
if (frac < tol)
return 1
else
return recip * denominator(recip)
end
end
Seems to be based on continued fractions although it became clear on looking at it again that it was wrong. (It worked for me because it would eventually just spit out infinity, which I handled outside, but it would be often really slow.) The value for tol doesn't really do anything except in the case of termination or for numbers that end up close. I don't think it's relatable to the tolerance for the real - rational conversion.
I've replaced it with an iterative version that is not only faster but I'm pretty sure it won't fail theoretically (d = 1 to start with and fractional part returns a positive, so recip is always >= 1) :
denom_iter(x d)
return d if d > maxd
frac = fractional part of x
recip = 1/frac
if (frac = 0)
return d
else
return denom_iter(recip d*recip)
end
end
What I'm curious to know if there's a way to pick the maxd that will ensure that it converts all values that are possible for a given tolerance. I'm assuming 1/tol but don't want to miss something. I'm also wondering if there's an way in this approach to actually limit the denominator size - this allows some denominators larger than maxd.
This can be considered a 2D minimization problem on error:
ArgMin ( r - q / p ), where r is real, q and p are integers
I suggest the use of Gradient Descent algorithm . The gradient in this objective function is:
f'(q, p) = (-1/p, q/p^2)
The initial guess r_o can be q being the closest integer to r, and p being 1.
The stopping condition can be thresholding of the error.
The pseudo-code of GD can be found in wiki: http://en.wikipedia.org/wiki/Gradient_descent
If the initial guess is close enough, the objective function should be convex.
As Jacob suggested, this problem can be better solved by minimizing the following error function:
ArgMin ( p * r - q ), where r is real, q and p are integers
This is linear programming, which can be efficiently solved by any ILP (Integer Linear Programming) solvers. GD works on non-linear cases, but lack efficiency in linear problems.
Initial guesses and stopping condition can be similar to stated above. Better choice can be obtained for individual choice of solver.
I suggest you should still assume convexity near the local minimum, which can greatly reduce cost. You can also try Simplex method, which is great on linear programming problem.
I give credit to Jacob on this.
A problem similar to this is solved in the Approximations section beginning ca. page 28 of Bill Gosper's Continued Fraction Arithmetic document. (Ref: postscript file; also see text version, from line 1984.) The general idea is to compute continued-fraction approximations of the low-end and high-end range limiting numbers, until the two fractions differ, and then choose a value in the range of those two approximations. This is guaranteed to give a simplest fraction, using Gosper's terminology.
The python code below (program "simpleden") implements a similar process. (It probably is not as good as Gosper's suggested implementation, but is good enough that you can see what kind of results the method produces.) The amount of work done is similar to that for Euclid's algorithm, ie O(n) for numbers with n bits, so the program is reasonably fast. Some example test cases (ie the program's output) are shown after the code itself. Note, function simpleratio(vlo, vhi) as shown here returns -1 if vhi is smaller than vlo.
#!/usr/bin/env python
def simpleratio(vlo, vhi):
rlo, rhi, eps = vlo, vhi, 0.0000001
if vhi < vlo: return -1
num = denp = 1
nump = den = 0
while 1:
klo, khi = int(rlo), int(rhi)
if klo != khi or rlo-klo < eps or rhi-khi < eps:
tlo = denp + klo * den
thi = denp + khi * den
if tlo < thi:
return tlo + (rlo-klo > eps)*den
elif thi < tlo:
return thi + (rhi-khi > eps)*den
else:
return tlo
nump, num = num, nump + klo * num
denp, den = den, denp + klo * den
rlo, rhi = 1/(rlo-klo), 1/(rhi-khi)
def test(vlo, vhi):
den = simpleratio(vlo, vhi);
fden = float(den)
ilo, ihi = int(vlo*den), int(vhi*den)
rlo, rhi = ilo/fden, ihi/fden;
izok = 'ok' if rlo <= vlo <= rhi <= vhi else 'wrong'
print '{:4d}/{:4d} = {:0.8f} vlo:{:0.8f} {:4d}/{:4d} = {:0.8f} vhi:{:0.8f} {}'.format(ilo,den,rlo,vlo, ihi,den,rhi,vhi, izok)
test (0.685, 0.695)
test (0.685, 0.7)
test (0.685, 0.71)
test (0.685, 0.75)
test (0.685, 0.76)
test (0.75, 0.76)
test (2.173, 2.177)
test (2.373, 2.377)
test (3.484, 3.487)
test (4.0, 4.87)
test (4.0, 8.0)
test (5.5, 5.6)
test (5.5, 6.5)
test (7.5, 7.3)
test (7.5, 7.5)
test (8.534537, 8.534538)
test (9.343221, 9.343222)
Output from program:
> ./simpleden
8/ 13 = 0.61538462 vlo:0.68500000 9/ 13 = 0.69230769 vhi:0.69500000 ok
6/ 10 = 0.60000000 vlo:0.68500000 7/ 10 = 0.70000000 vhi:0.70000000 ok
6/ 10 = 0.60000000 vlo:0.68500000 7/ 10 = 0.70000000 vhi:0.71000000 ok
2/ 4 = 0.50000000 vlo:0.68500000 3/ 4 = 0.75000000 vhi:0.75000000 ok
2/ 4 = 0.50000000 vlo:0.68500000 3/ 4 = 0.75000000 vhi:0.76000000 ok
3/ 4 = 0.75000000 vlo:0.75000000 3/ 4 = 0.75000000 vhi:0.76000000 ok
36/ 17 = 2.11764706 vlo:2.17300000 37/ 17 = 2.17647059 vhi:2.17700000 ok
18/ 8 = 2.25000000 vlo:2.37300000 19/ 8 = 2.37500000 vhi:2.37700000 ok
114/ 33 = 3.45454545 vlo:3.48400000 115/ 33 = 3.48484848 vhi:3.48700000 ok
4/ 1 = 4.00000000 vlo:4.00000000 4/ 1 = 4.00000000 vhi:4.87000000 ok
4/ 1 = 4.00000000 vlo:4.00000000 8/ 1 = 8.00000000 vhi:8.00000000 ok
11/ 2 = 5.50000000 vlo:5.50000000 11/ 2 = 5.50000000 vhi:5.60000000 ok
5/ 1 = 5.00000000 vlo:5.50000000 6/ 1 = 6.00000000 vhi:6.50000000 ok
-7/ -1 = 7.00000000 vlo:7.50000000 -7/ -1 = 7.00000000 vhi:7.30000000 wrong
15/ 2 = 7.50000000 vlo:7.50000000 15/ 2 = 7.50000000 vhi:7.50000000 ok
8030/ 941 = 8.53347503 vlo:8.53453700 8031/ 941 = 8.53453773 vhi:8.53453800 ok
24880/2663 = 9.34284641 vlo:9.34322100 24881/2663 = 9.34322193 vhi:9.34322200 ok
If, rather than the simplest fraction in a range, you seek the best approximation given some upper limit on denominator size, consider code like the following, which replaces all the code from def test(vlo, vhi) forward.
def smallden(target, maxden):
global pas
pas = 0
tol = 1/float(maxden)**2
while 1:
den = simpleratio(target-tol, target+tol);
if den <= maxden: return den
tol *= 2
pas += 1
# Test driver for smallden(target, maxden) routine
import random
totalpass, trials, passes = 0, 20, [0 for i in range(20)]
print 'Maxden Num Den Num/Den Target Error Passes'
for i in range(trials):
target = random.random()
maxden = 10 + round(10000*random.random())
den = smallden(target, maxden)
num = int(round(target*den))
got = float(num)/den
print '{:4d} {:4d}/{:4d} = {:10.8f} = {:10.8f} + {:12.9f} {:2}'.format(
int(maxden), num, den, got, target, got - target, pas)
totalpass += pas
passes[pas-1] += 1
print 'Average pass count: {:0.3}\nPass histo: {}'.format(
float(totalpass)/trials, passes)
In production code, drop out all the references to pas (etc.), ie, drop out pass-counting code.
The routine smallden is given a target value and a maximum value for allowed denominators. Given maxden possible choices of denominators, it's reasonable to suppose that a tolerance on the order of 1/maxden² can be achieved. The pass-counts shown in the following typical output (where target and maxden were set via random numbers) illustrate that such a tolerance was reached immediately more than half the time, but in other cases tolerances 2 or 4 or 8 times as large were used, requiring extra calls to simpleratio. Note, the last two lines of output from a 10000-number test run are shown following the complete output of a 20-number test run.
Maxden Num Den Num/Den Target Error Passes
1198 32/ 509 = 0.06286837 = 0.06286798 + 0.000000392 1
2136 115/ 427 = 0.26932084 = 0.26932103 + -0.000000185 1
4257 839/2670 = 0.31423221 = 0.31423223 + -0.000000025 1
2680 449/ 509 = 0.88212181 = 0.88212132 + 0.000000486 3
2935 440/1853 = 0.23745278 = 0.23745287 + -0.000000095 1
6128 347/1285 = 0.27003891 = 0.27003899 + -0.000000077 3
8041 1780/4243 = 0.41951449 = 0.41951447 + 0.000000020 2
7637 3926/7127 = 0.55086292 = 0.55086293 + -0.000000010 1
3422 27/ 469 = 0.05756930 = 0.05756918 + 0.000000113 2
1616 168/1507 = 0.11147976 = 0.11147982 + -0.000000061 1
260 62/ 123 = 0.50406504 = 0.50406378 + 0.000001264 1
3775 52/3327 = 0.01562970 = 0.01562750 + 0.000002195 6
233 6/ 13 = 0.46153846 = 0.46172772 + -0.000189254 5
3650 3151/3514 = 0.89669892 = 0.89669890 + 0.000000020 1
9307 2943/7528 = 0.39094049 = 0.39094048 + 0.000000013 2
962 206/ 225 = 0.91555556 = 0.91555496 + 0.000000594 1
2080 564/1975 = 0.28556962 = 0.28556943 + 0.000000190 1
6505 1971/2347 = 0.83979548 = 0.83979551 + -0.000000022 1
1944 472/ 833 = 0.56662665 = 0.56662696 + -0.000000305 2
3244 291/1447 = 0.20110574 = 0.20110579 + -0.000000051 1
Average pass count: 1.85
Pass histo: [12, 4, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
The last two lines of output from a 10000-number test run:
Average pass count: 1.77
Pass histo: [56659, 25227, 10020, 4146, 2072, 931, 497, 233, 125, 39, 33, 17, 1, 0, 0, 0, 0, 0, 0, 0]

Generating a repeatable pseudo-random number based coordinates

I need to generate repeatable pseudo random numbers based on a set of coordinates, so that with a given seed, I will always generate the same value for a specific coordinate.
I figured I'd use something like this for the seed:
/* 64bit seed value*/
struct seed_cord {
uint16 seed;
uint16 coord_x_int;
uint16 coord_y_int;
uint8 coord_x_frac;
uint8 coord_y_frac;
}
Where coord_x_int is the integer part of the coordinate, and the fraction part is given by coord_x_frac / 0xFF. seed is a randomly pre-determined value.
But I must admit, trying to understand all the intricacies of PRNGs is a little overwhelming. What would be a good generator for what I'm attempting?
I tested out Java's PRNG using using this scheme in a quick groovy script, with the following result:
Obviously, this is hardly decent randomness.
The script I used was:
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
short shortSeed = new Random().next(16) as short
def image = new BufferedImage(512, 512, BufferedImage.TYPE_BYTE_GRAY)
def raster = image.getRaster()
//x
(0..1).each{ x ->
(0..255).each{ xFrac ->
//y
(0..1).each{ y ->
(0..255).each{ yFrac ->
long seed = (shortSeed as long) << 48 |
(x as long) << 32 |
(y as long) << 16 |
(xFrac as long) << 8 |
(yFrac as long)
def value = new Random(seed).next(8)
raster.setSample( (x? xFrac+256 : xFrac), (y? yFrac+256 : yFrac), 0 , value)
}}}}
ImageIO.write(image, "PNG", new File("randomCoord.png"))
If you're really only looking at 512x512, then that's uh... 218 pixels you're interested in.
There's plenty of space for that kind of population with good ole MD5 (128 bit output).
You can just take the lowest 32 bits for an integer if that's the kind of output you need. Really, any sort of hashing algorithm that has an output space at least as large as an int will do.
Now, you can do all sorts of fun stuff if you're paranoid. Start with a hash of your coordinates, then feed the result into a secure random number generator (java.security.SecureRandom). Then hash it 1000 times with a salt that's your birthday concatenated (x+y) times.
Joking aside, random number generators don't necessarily have wildly varying results based on small variations of the seed. They're designed to have a really, super duper long chain of generated numbers before they start repeating, while having those chains pretty evenly distributed among the number space.
On the other hand, the SecureRandom is designed to have the additional feature of being chaotic in regard to the seed.
Most languages have a PRNG package (or two) that lets you initialize the generator with a specific seed. PRNGs can also often be found as part of a larger cryptographic package; they tend to be a bit stronger than those found in general-purpose libraries.
I would take a program like this one I have created and then modify it to pick coordinates:
REM $DYNAMIC
COMMON SHARED n%, rbuf%, sz%, sw%, p1$
DECLARE SUB initialize ()
DECLARE SUB filbuf ()
DECLARE SUB setup ()
DECLARE FUNCTION Drnd# ()
DECLARE SUB core ()
DECLARE SUB modify ()
DIM SHARED pad1(340) AS STRING * 1
DIM SHARED trnsltr(66) AS STRING * 1 ' translates a 0-67 value into a pad character
DIM SHARED trnslt(255) AS INTEGER 'translates a pad value to 0-67 value -1 if error
DIM SHARED moders(26) AS INTEGER 'modding function prim number array
DIM SHARED moders2(26) AS INTEGER 'modding function prim number array
DIM SHARED ranbuf(1 TO 42) AS DOUBLE 'random number buffer if this is full and rbuf %>0
REM then this buffer is used to get new random values
REM rbuf% holds the index of the next random number to be used
REM subroutine setup loads the prime number table
REM from the data statements to be used
REM as modifiers in two different ways (or more)
REM subroutine initialize primes the pad array with initial values
REM transfering the values from a string into an array then
REM makes the first initial scrambling of this array
REM initializing pad user input phase:
CLS
INPUT "full name of file to be encrypted"; nam1$
INPUT "full name of output file"; nam2$
INPUT "enter password"; p2$
rbuf% = 0
n% = 0: sw% = 0
p3$ = STRING$(341, "Y")
p1$ = "Tfwd+-$wiHEbeMN<wjUHEgwBEGwyIEGWYrg3uehrnnqbwurt+>Hdgefrywre"
p1$ = p2$ + p1$ + p3$
PRINT "hit any key to continue any time after a display and after the graphic display"
p1$ = LEFT$(p1$, 341)
sz% = LEN(p1$)
CALL setup
CALL initialize
CLS
ibfr$ = STRING$(512, 32)
postn& = 1
OPEN nam1$ FOR BINARY AS #1
OPEN nam2$ FOR BINARY AS #2
g& = LOF(1)
max& = g&
sbtrct% = 512
WHILE g& > 0
LOCATE 1, 1
PRINT INT(1000 * ((max& - g&) / max&)) / 10; "% done";
IF g& < 512 THEN
ibfr$ = STRING$(g&, 32)
sbtrct% = g&
END IF
GET #1, postn&, ibfr$
FOR ste% = 1 TO LEN(ibfr$)
geh% = INT(Drnd# * 256)
MID$(ibfr$, ste%, 1) = CHR$(geh% XOR ASC(MID$(ibfr$, ste%, 1)))
NEXT ste%
PUT #2, postn&, ibfr$
postn& = postn& + sbtrct%
g& = g& - sbtrct%
WEND
CLOSE #2
CLOSE #1
PRINT "hit any key to exit"
i$ = ""
WHILE i$ = "": i$ = INKEY$: WEND
SYSTEM
END
DATA 3,5,7,9,11,13,17,19
DATA 23,29,33,37,43,47
DATA 53,59,67,71,73,79,83
DATA 89,91,97,101,107,109
DATA 43,45,60,62,36
REM $STATIC
SUB core
REM shuffling algorythinm
FOR a% = 0 TO 339
m% = (a% + 340) MOD 341: bez% = trnslt(ASC(pad1(340)))
IF n% MOD 3 = 0 THEN pad1(340) = trnsltr((2 * trnslt(ASC(pad1(a%))) + 67 - trnslt(ASC(pad1(m%)))) MOD 67)
IF n% MOD 3 = 1 THEN pad1(340) = trnsltr((2 * (67 - trnslt(ASC(pad1(a%)))) + 67 - trnslt(ASC(pad1(m%)))) MOD 67)
IF n% MOD 3 = 2 THEN pad1(340) = trnsltr(((2 * trnslt(ASC(pad1(a%))) + 67 - trnslt(ASC(pad1(m%)))) + moders(n% MOD 27)) MOD 67)
pad1(a% + 1) = pad1(m%): n% = (n% + 1) MOD 32767
pad1(a%) = trnsltr((bez% + trnslt(ASC(pad1(m%)))) MOD 67)
NEXT a%
sw% = (sw% + 1) MOD 32767
END SUB
FUNCTION Drnd#
IF rbuf% = 0 THEN
CALL core
CALL filbuf
IF sw% = 32767 THEN CALL modify
END IF
IF rbuf% > 0 THEN yut# = ranbuf(rbuf%)
rbuf% = rbuf% - 1
Drnd# = yut#
END FUNCTION
SUB filbuf
q% = 42: temp# = 0
WHILE q% > 0
FOR p% = 1 TO 42
k% = (p% - 1) * 8
FOR e% = k% TO k% + 7
temp# = temp# * 67: hug# = ABS(trnslt(ASC(pad1(e%)))): temp# = temp# + hug#
NEXT e%
IF temp# / (67 ^ 8) >= 0 AND q% < 43 THEN
ranbuf(q%) = temp# / (67 ^ 8): q% = q% - 1
END IF
temp# = 0
NEXT p%
WEND
rbuf% = 42
END SUB
SUB initialize
FOR a% = 0 TO 340
pad1(a%) = MID$(p1$, a% + 1, 1)
NEXT a%
FOR a% = 0 TO 340
LOCATE 1, 1
IF a% MOD 26 = 0 THEN PRINT INT((340 - a%) / 26)
sum% = 0
FOR b% = 0 TO 340
qn% = INT(Drnd# * 81)
op% = INT(qn% / 3)
qn% = qn% MOD 3
IF qn% = 0 THEN sum% = sum% + trnslt(ASC(pad1(b%)))
IF qn% = 1 THEN sum% = sum% + (67 + 66 - trnslt(ASC(pad1(b%)))) MOD 67
IF qn% = 2 THEN sum% = sum% + trnslt(ASC(pad1(b%))) + moders(op%)
NEXT b%
pad1(a%) = trnsltr(sum% MOD 67)
NEXT a%
n% = n% + 1
END SUB
SUB modify
REM modifier shuffling routine
q% = 26
temp# = 0
WHILE q% > -1
FOR p% = 1 TO 27
k% = (p% - 1) * 4 + 3
FOR e% = k% TO k% + 3
temp# = temp# * 67
hug# = ABS(trnslt(ASC(pad1(e%))))
temp# = temp# + hug#
NEXT e%
IF (temp# / (67 ^ 4)) >= 0 AND q% > -1 THEN
SWAP moders(q%), moders(INT(27 * (temp# / (67 ^ 4))))
q% = q% - 1
END IF
temp# = 0
NEXT p%
WEND
END SUB
SUB setup
FOR a% = 0 TO 26
READ moders(a%)
moders2(a%) = moders(a%)
NEXT a%
REM setting up tables and modder functions
FOR a% = 0 TO 25
trnsltr(a%) = CHR$(a% + 97)
trnsltr(a% + 26) = CHR$(a% + 65)
NEXT a%
FOR a% = 52 TO 61
trnsltr(a%) = CHR$(a% - 4)
NEXT a%
FOR a% = 62 TO 66
READ b%
trnsltr(a%) = CHR$(b%)
NEXT a%
FOR a% = 0 TO 255
trnslt(a%) = -1
NEXT a%
FOR a% = 0 TO 66
trnslt(ASC(trnsltr(a%))) = a%
NEXT a%
RESTORE
END SUB
the call to drand# gives you random numbers from 0 to 1 simply multiply that by your needed range for each vector needed p2$ is the password that is passed to the password handler which combines it with some other random characters and then caps the size to a certain limit p1$ is where the final modified password is contained
drand# itself calls another sub which is actually a clone of itself with some shuffling of
sorts that works to ensure that the numbers being produced are truly random there is also a table of values that are added in to the values being added all this in total makes the RNG many many more times random with than without.
this RNG has a very high sensitivity to slight differences in password initially set you must however make an intial call to setup and initialize to "bootstrap" the random number generator this RNG will produce Truly random numbers that will pass all tests of randomness
more random even then shuffling a deck of cards by hand , more random than rolling a dice..
hope this helps using the same password will result in the same sequnece of vectors
This program would have to be modified a bit though to pick random vectors rather than
it's current use as a secure encryption random number generator...
You can use encryption for this task, for example AES. Use your seed as the password, struct with coordinates as the data block and encrypt it. The encrypted block will be your random number (you can actually use any part of it). This approach is used in the Fortuna PRNG. The same approach can be used for disk encryption where random access of data is needed (see Random access encryption with AES In Counter mode using Fortuna PRNG:)

Resources