calculate numbers in array (run length decoding) - c#

int[] bytes = new int[9] { 123, 5, 65, 123, 6, 77, 123, 4, 101 };
int count = 1;
for (int i = 1; i < bytes.Length; i++)
{
if (bytes[i] == 123)
{
count++;
}
else
{
Console.WriteLine(bytes[i]);
}
}
Console.ReadLine();
Im a beginner in programming.
The 123 is some type of "marker"
I dont know how to do a console output like this: 65 65 65 65 65 77 77 77 77 77 77 101 101 101 101
I would appreciate any help

To decode anything, you really need a specification of what that something is. In this case, I could speculate that:
123 means "the following two bytes X and Y should be interpreted as X instances (0-255) of the payload Y"
so you would parse one byte, if it isn't 123: give up because you don't have any other rules to follow, but otherwise, read X and Y, and output X copies of the value Y
In pseudo-code:
while(TryTakeByte(out val)))
switch val
123:
if (!TryTakeByte(out x) || !TryTakeByte(out y)) FailEndOfStream()
for (i from 0 to x)
write y
default:
FailNoClueWhatToDo() // refer to protocol specification

Related

How to Parse received Hex bytes into readable string

As the title says, I've been working on MiFare Classic reading a card.
I'm using the MiFare v1.1.3 Library from NuGet
and it returns a byte array, which I parse to readable Hex strings, by looping thru it.
Here's the code snippet:
int sector = 1;
int block = 0;
int size = 16;
var data = await localCard.GetData(sector, block, size);
string hexString = "";
for (int i = 0; i < data.Length; i++)
{
hexString += data[i].ToString("X2") + " ";
}
// hexString returns 84 3D 17 B0 1E 08 04 00 02 63 B5 F6 B9 BE 77 1D
Now, how can I parse it properly?
I've tried parsing it into ASCII, ANSI, Int, Int64, Base64, Long
and all of them didn't match the 'data' that it's suppose to contain
EDIT:
The expected output: 1206058
HEX String returned: 84 3D 17 B0 1E 08 04 00 02 63 B5 F6 B9 BE 77 1D
I've checked the source code
it looks like both Task<byte[]> GetData Task SetData methods do not have any special logic to transform the data. Data are just saved (and read) as byte[]
I suppose that you have to contact author/company that has wrote data you are trying to read.
The expected output: 1206058
Looks strange since you are reading 16 bytes size = 16 and expecting 7 characters to be read.
Is it possible that block or sector values are incorrect ?
I have written a simple program to solve your problem. Perhaps this is what you want to achieve:
// The original byte data array; some random data
byte[] data = { 0, 1, 2, 3, 4, 85, 128, 255 };
// Byte data -> Hex string
StringBuilder hexString = new StringBuilder();
foreach (byte item in data)
{
hexString.Append($"{item.ToString("X2")} ");
}
Console.WriteLine(hexString.ToString().Trim());
// Hex string -> List of bytes
string[] hexArray = hexString.ToString().Trim().Split(' ');
List<byte> dataList = new List<byte>();
foreach (string item in hexArray)
{
dataList.Add(byte.Parse(item, System.Globalization.NumberStyles.HexNumber));
}
dataList.ForEach(b => Console.Write($"{b} "));
Console.WriteLine();
If it is not the right solution please provide us more info about your problem.
If var data potentially is string - you can reverse it from hex by:
// To Hex
byte[] plainBytes = Encoding.ASCII.GetBytes("MiFare v1.1.3");
string hexString = "";
for (int i = 0; i < plainBytes.Length; i++)
hexString += plainBytes[i].ToString("X2") + " ";
Console.WriteLine(hexString); // Result: "4D 69 46 61 72 65 20 76 31 2E 31 2E 33"
// From Hex
hexString = hexString.Replace(" ", ""); // Remove whitespaces to have "4D69466172652076312E312E33"
byte[] hexBytes = new byte[hexString.Length / 2];
for (int i = 0; i < hexString.Length / 2; i++)
hexBytes[i] = Convert.ToByte(hexString.Substring(2 * i, 2), 16);
string plainString = Encoding.ASCII.GetString(hexBytes);
Console.WriteLine(plainString); // Result: "MiFare v1.1.3"
Just, probably, should be needed to define correct Encoding.

Method changing the value of a list wrongly

So I wrote a test code (trying to teach myself how to make sorting algorithms), which looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static string Compile (List<int> array)
{
string output = "";
foreach (var item in array)
{
output += item.ToString() + " ";
}
return output;
}
static List<int> InsertSort(List<int> listToSort)
{
List<int> deliverList = new List<int>();
deliverList = listToSort;
int j = 0;
int iterator = 0;
for (int i = 1; i < deliverList.Count; i++)
{
j = i;
while(j>0)
{
if(deliverList[j] < deliverList[j-1])
{
int temp = deliverList[j - 1];
deliverList[j - 1] = deliverList[j];
deliverList[j] = temp;
}
Console.WriteLine("Iteration #[" + iterator.ToString() + "]: " + Compile(deliverList));
iterator++;
j--;
}
}
return deliverList;
}
static void Main(string[] args)
{
List<int> unsorted = new List<int>();
List<int> sorted = new List<int>();
Random random = new Random();
for (int i = 0; i < 10; i++)
{
unsorted.Add(random.Next(0, 100));
}
sorted = InsertSort(unsorted);
Console.WriteLine("Unsorted Array: " + Compile(unsorted));
Console.WriteLine("Sorted Array: " + Compile(sorted));
Console.ReadKey();
}
}
}
For some reason, when I use the InsertSort method on the "sorted" array, the "unsorted" array is also changed, outputting the sorted array two times and not letting me see the unsorted one. What exactly is happening here?
PS: Compile is just a simple method that compiles a list into a string with the elements separated by spaces.
You have the code deliverList = listToSort; which makes deliverList reference the same list as listToSort. They become synonyms.
Instead you should write:
List<int> deliverList = listToSort.ToList();
That will make a copy of the list - and now they will both be different.
Your code now would output:
Iteration #[0]: 52 88 93 69 35 21 63 47 2 17
Iteration #[1]: 52 88 93 69 35 21 63 47 2 17
...
Iteration #[43]: 2 17 21 35 47 52 63 69 88 93
Iteration #[44]: 2 17 21 35 47 52 63 69 88 93
Unsorted Array: 88 52 93 69 35 21 63 47 2 17
Sorted Array: 2 17 21 35 47 52 63 69 88 93
you need to make a copy of the list
List<int> deliverList = listToSort.Select(x=>x);

distribute values of list 1 unequal lenth over list 2 in linear/evenly fashion

I have 2 List<float> of unequal length.
Scores and Grades.
Depending on the configuration one or the other list is greater than the other.
There are 2 scenarios:
Use case 1: 60 scores and 50 grades - 1 to 6 with tenth grades -
I have to distribute 60 scores over 50 grades in an even way.
Thus many grades will have multiple related consecutive scores (1:N relation concerning data structure)
Use case 2: 40 scores and 50 grades - 1 to 6 with tenth grades -
I have to distribute 40 scores over 50 grades in an even way.
Thus 10 grades must be removed (50 - 40) evenly to get a 1:1 relation data structure between scores and grades.
What algorithm`s are available to me that I can solve the problem with C#?
I have written down here the result data I would expect to look like when the implemented algorythm is run.
Use case 1 sample result data:
Scores Grade
0 6
1 5,9
2 - 3 5,8
4 5,7
5 5,6
6 5,5
7 5,4
8 - 9 5,3
10 5,2
11 5,1
12 5
13 4,9
14 - 15 4,8
16 4,7
17 4,6
18 4,5
19 4,4
20 - 21 4,3
22 4,2
23 4,1
24 4
25 3,9
26 - 27 3,8
28 3,7
29 3,6
30 3,5
31 3,4
32 - 33 3,3
34 3,2
35 3,1
36 3
37 2,9
38 - 39 2,8
40 2,7
41 2,6
42 2,5
43 2,4
44 - 45 2,3
46 2,2
47 2,1
48 2
49 1,9
50 - 51 1,8
52 1,7
53 1,6
54 1,5
55 1,4
56 - 57 1,3
58 1,2
59 1,1
60 1
Use case 2 sample result data:
Score Grade
0 6
1 5,9
2 5,8
3 5,6
4 5,5
5 5,4
6 5,3
7 5,1
8 5
9 4,9
10 4,8
11 4,6
12 4,5
13 4,4
14 4,3
15 4,1
16 4
17 3,9
18 3,8
19 3,6
20 3,5
21 3,4
22 3,3
23 3,1
24 3
25 2,9
26 2,8
27 2,6
28 2,5
29 2,4
30 2,3
31 2,1
32 2
33 1,9
34 1,8
35 1,6
36 1,5
37 1,4
38 1,3
39 1,1
40 1
C# converted code for y = f(x) ;-)
int x, y, accum;
int scores = 33;
int grades = 51;
float[] gradesArray = new float[grades];
float[] scoresArray = new float[scores];
for (y = 0; y < grades; y++)
gradesArray[y] = 6.0f - y / 10.0f;
accum = scores / 2;
y = 0;
for (x = 0; x < scores; x++)
{
scoresArray[x] = gradesArray[y];
accum += grades;
while (accum >= scores)
{
y++;
accum -= scores;
}
}
Assume gradesArray is an input array indexed by y, and scoresArray is the output array indexed by x. To generate the output array, for each index in the output array, you need to select the corresponding value from the input array. In pseudo-code:
scoresArray[x] = gradesArray[y] where y = f(x)
In words, each output value scoresArray[x] is taken from location y in the input array gradesArray[y], where y is some function of x. And what is that function? Well it's a line.
Here's some sample code that uses a line drawing algorithm to solve use case 1:
int x, y, accum;
int scores = 61;
int grades = 51;
float[] gradesArray = new float[grades];
float[] scoresArray = new float[scores];
for (y = 0; y < grades; y++)
gradesArray[y] = 6.0f - y / 10.0f;
accum = (scores-1) / 2;
y = 0;
for (x = 0; x < scores; x++)
{
scoresArray[x] = gradesArray[y];
accum += (grades-1);
y += accum / (scores-1);
accum %= (scores-1);
}
To adapt the code for use case 2, just change int scores = 61 to int scores = 41.

Extracting data packet out of byte buffer

I have a buffer of length 256 that receives byte sequences from bluetooth. The actual packet that I need to extract is starting and ending with byte 126. I want to extract the latest packet in the buffer using LINQ.
What I am doing now is checking for last index of 126 and then count backward until I reach another 126. There are some pitfalls as well, for example, two adjacent packet can result in two bytes of 126 next to eachother.
Here is a sample of buffer:
126 6 0 5 232 125 93 126 126 69 0
0 1 0 2 2 34 6 0 5 232 125
93 126 126 69 0 0 1 0 2 2 34
6 0 5 232 125 93 126 126 69 0 0
1 0 2 2 34 6 0 5 232 125 93
126 126 69 0 0
So the information I have is:
Packet starts and ends with byte value of 126
the next byte after the starting index does have value of 69
the 3 last byte right befor the ending byte of 126 is a CRC of the whole packet that I know how to calculate, so after extracting a packet I can check this CRC to see if I have the right packet
So at the end I want to have an array or list that contains the correct packet. for example:
126 69 0 0 1 0 2 2 34 6 0 5 232 125 93 126
Can you give me a fast soloution of extracting this packet from buffer?
This is what I'v tried so far....it fails as it cant really return the correct packet I am looking for:
var data = ((byte[])msg.Obj).ToList(); //data is the buffer
byte del = 126; //delimeter or start/end byte
var lastIndex = data.LastIndexOf(del);
var startIndex = 0;
List<byte> tos = new List<byte>(); //a new list to store the result (packet)
//try to figure out start index
if(data[lastIndex - 1] != del)
{
for(int i = lastIndex; i > 0; i--)
{
if(data[i] == del)
{
startIndex = i;
}
}
//add the result in another list
for(int i = 0; i <= lastIndex - startIndex; i++)
{
tos.Add(data[i]);
}
string shit = string.Empty;
foreach (var b in tos)
shit += (int)b + ", ";
//print result in a textbox
AddTextToLogTextView(shit + "\r\n");
}
Solutions
I've prepared three possible solution of taking the last packet from input buffor:
Using LINQ
public static byte[] GetLastPacketUsingLINQ(byte[] input, byte delimiter)
{
var part = input.Reverse()
.SkipWhile(i => i != delimiter)
.SkipWhile(i => i == delimiter)
.TakeWhile(i => i != delimiter)
.Reverse();
return (new byte[] { delimiter }).Concat(part).Concat(new byte[] { delimiter }).ToArray();
}
Using string.Split
public static byte[] GetLastPacketUsingString(byte[] input, byte delimiter)
{
var encoding = System.Text.Encoding.GetEncoding("iso-8859-1");
string inputString = encoding.GetString(input);
var parts = inputString.Split(new[] { (char)delimiter }, StringSplitOptions.RemoveEmptyEntries);
return encoding.GetBytes((char)delimiter + parts[parts.Length - 2] + (char)delimiter);
}
Using while loop and indexers
public static byte[] GetLastPacketUsingIndexers(byte[] input, byte delimiter)
{
int end = input.Length - 1;
while (input[end--] != delimiter) ;
int start = end - 1;
while (input[start--] != delimiter) ;
var result = new byte[end - start];
Array.Copy(input, start + 1, result, 0, result.Length);
return result;
}
Performance
I've also performed some very simple performance tests. Here are the results:
LINQ version result:
126 69 0 0 1 0 2 2 34 6 0 5 232 125 93 126
String version result:
126 69 0 0 1 0 2 2 34 6 0 5 232 125 93 126
Indexers version result:
126 69 0 0 1 0 2 2 34 6 0 5 232 125 93 126
LINQ version time: 64ms (106111 ticks)
String version time: 2ms (3422 ticks)
Indexers version time: 1ms (2359 ticks)
Conclusion
As you can see, the simplest one is also the best one here.
You may think that LINQ is an answer for every problem, but some time it's really better idea to write simpler solution manually instead of using LINQ methods.
Using LINQ this can be done in a single line of code if the following two rules can be applied to the buffer:
The buffer contains at least one complete package surrounded by the
given delimiter.
Each packet contains at least one byte of data.
Here is the code:
var data = (byte[])msg.Obj;
byte delimiter = 126;
var packet = data.Reverse()
.SkipWhile(b => b != delimiter)
.SkipWhile(b => b == delimiter)
.TakeWhile(b => b != delimiter)
.Reverse();
(Ok, this was more than a single line because I splitted it into multiple lines for better readability.)
EDIT: Removed the call to Take(1) because that would always return an empty sequence. The result however doesn't contain delimiter this way.
And here is how it works:
Since we want to find the last packet we can reverse the data:
var reversed = data.Reverse();
The buffer can end with a packet which is not complete yet. So let's skip that:
reversed = reversed.SkipWhile(b => b != delimiter);
reversed is now either empty or it starts with delimiter. Since we assumed that the buffer always contains at least one complete packet we can already take the next byte for our result because we know it is the delimiter:
var packet = reversed.Take(1);
In the sequence we can now skip one byte. If the delimiter we found was actually the start of a new packet the remaining sequence will start with another delimiter so we have to skip that also:
reversed = reversed.Skip(1);
if (reversed.First() == delimiter)
{
reversed.Skip(1);
}
Since we know that a packet can not be empty because it contains a 3 bytes CRC we could have written:
reversed = reversed.SkipWhile(b => b == delimiter);
Now the actual data follows:
packet = packet.Concat(reversed.TakeWhile(b => b != delimiter));
reversed = reversed.SkipWhile(b => b != delimiter);
The next byte is the delimiter which marks the start of the packet:
packet = packet.Concat(reversed.Take(1));
The last thing to do is to reverse the result again:
packet = packet.Reverse();
Maybe you want to put this into a method:
public IEnumerable<byte> GetPacket(byte[] data, byte delimiter)
{
yield return delimiter;
foreach (byte value in data.Reverse()
.SkipWhile(b => b != delimiter)
.SkipWhile(b => b == delimiter)
.TakeWhile(b => b != delimiter))
{
yield return value;
}
yield return delimiter;
}
You will have to call Reverse on the return value of this method.
If performance matters you can use the same algorithm on the underlying array. This way it will be about 20 times faster:
int end = data.Length - 1;
while (data[end] != delimiter)
end--;
while (data[end] == delimiter)
end--;
int start = end;
while (data[start] != delimiter)
start--;
byte[] result = new byte[end - start + 2]; // +2 to include delimiters
Array.Copy(data, start, result, 0, result.Length);
There actually are various ways to solve your question, the simplest idea is detect double 126(0x7e), and doesn't matter other things such like CRC.
The basic implemention of this concept would be like this
Code as simple
var list=new List<byte[]>();
int i=0, j=0;
for(; i<data.Length; ++i)
if(i>0&&0x7e==data[i]&&0x7e==data[i-1]) {
list.Add(data.Skip(j).Take(i-j).ToArray());
j=i;
}
list.Add(data.Skip(j).Take(i-j).ToArray());
Base on my old answer of Konami Code in C#, and it even used to solve this question: Double characters shown when typing special characters while logging keystrokes in c#.
Code with a sequence detector
public partial class TestClass {
public static void TestMethod() {
var data=(
new[] {
126, 6, 0, 5, 232, 125, 93, 126,
126, 69, 0, 0, 1, 0, 2, 2, 34, 6, 0, 5, 232, 125, 93, 126,
126, 69, 0, 0, 1, 0, 2, 2, 34, 6, 0, 5, 232, 125, 93, 126,
126, 69, 0, 0, 1, 0, 2, 2, 34, 6, 0, 5, 232, 125, 93, 126,
126, 69, 0, 0
}).Select(x => (byte)x).ToArray();
var list=new List<List<byte>>();
foreach(var x in data) {
if(list.Count<1||SequenceCapturer.Captured((int)x))
list.Add(new List<byte>());
list.Last().Add(x);
}
foreach(var byteList in list)
Debug.Print("{0}", byteList.Select(x => x.ToString("x2")).Aggregate((a, b) => a+"\x20"+b));
}
}
public class SequenceCapturer {
public int Count {
private set;
get;
}
public int[] Sequence {
set;
get;
}
public bool Captures(int value) {
for(var i=Sequence.Length; i-->0; ) {
if(Sequence[i]!=value) {
if(0==i)
Count=0;
continue;
}
if(Count!=i)
continue;
++Count;
break;
}
var x=Sequence.Length==Count;
Count=x?0:Count;
return x;
}
public SequenceCapturer(int[] newSequence) {
Sequence=newSequence;
}
public SequenceCapturer()
: this(new[] { 0x7e, 0x7e }) {
}
public static bool Captured(int value) {
return Instance.Captures(value);
}
public static SequenceCapturer Instance=new SequenceCapturer();
}
Or if you would like to write it full in Linq, you might want to try the following. You even don't need to use List, packetArray gives you an array of byte arrays directly.
The lets are intended to break the code into lines, otherwise it would be an extreme long statement in one line. If you consider one line is the best, then I will.
Code of packetArray
var packetArray=(
from sig in new[] { new byte[] { 0x7e, 0x7e } }
let find=new Func<byte[], int, IEnumerable<byte>>((x, i) => x.Skip(i).Take(sig.Length))
let isMatch=new Func<IEnumerable<byte>, bool>(sig.SequenceEqual)
let filtered=data.Select((x, i) => 0==i||isMatch(find(data, i-1))?i:~0)
let indices=filtered.Where(i => ~0!=i).Concat(new[] { data.Length }).ToArray()
from index in Enumerable.Range(1, indices.Length-1)
let skipped=indices[index-1]
select data.Skip(skipped).Take(indices[index]-skipped).ToArray()).ToArray();
Code for output
foreach(var byteArray in packetArray)
Debug.Print("{0}", byteArray.Select(x => x.ToString("x2")).Aggregate((a, b) => a+"\x20"+b));
However, even in the same concept of solution, there would be various ways as I mentioned before. I'd strongly recommend that don't involve additional conditions like something about CRC, which might make things more complicated.
Since you're looking for the last packet, it's much easier to reverse the byte[] and look for the first packet. Your two packet delimiters are not just 126. They are 126, 69 for the start and 126, 126 for the end unless the end of the packet is the last byte recieved, which makes the end delimiter 126.
I would suggest using a method simular to this:
public static byte[] GetMessage(byte[] msg)
{
//Set delimiters
byte delimit = 126;
byte startDelimit = 69;
//Reverse the msg so we can find the last packet
List<byte> buf = msg.Reverse().ToList();
//set indices to impossible values to check for failures
int startIndex = -1;
int endIndex = -1;
//loop through the message
for (int i = 0; i < buf.Count - 1; i++)
{
//find either a double 126, or 126 as the last byte (message just ended)
if (buf[i] == delimit && (buf[i + 1] == delimit || i == 0))
{
if (i == 0)
{
startIndex = i;
i++;
}
else
{
startIndex = i + 1;
i += 2;
}
continue;
}
//Only process if we've found the start index
if (startIndex != -1)
{
//check if the byte is 69 followed by 126
if (buf[i] == startDelimit && buf[i + 1] == delimit)
{
endIndex = i + 1;
break;
}
}
}
//make sure we've found a message
if (!(startIndex == -1 || endIndex==-1))
{
//get the message and reverse it to be the original packet
byte[] revRet = new byte[endIndex - startIndex];
Array.Copy(buf.ToArray(), startIndex, revRet, 0, endIndex - startIndex);
return revRet.Reverse().ToArray();
}
return new byte[1];
}
I'm not totally sure if the indices of the copy are completely correct, but this should be the jist of it.
since you may receive incomplete data, you must store the last incomplete buffer.
this is sample case, First Receive :
126, 6, 0, 5, 232, 125, 93, 126, 126, 69, 0,
0, 1, 0, 2, 2, 34, 6 , 0 , 5 , 232, 125,
93, 126, 126, 69, 0, 0, 1 , 0, 2, 2, 34,
6, 0, 5, 232, 125, 93, 126, 126, 69, 0, 0 ,
1, 0, 2, 2, 34, 6, 0, 5, 232, 125, 93,
126, 126, 69, 0, 0
the second stream :
69, 0, 0 , 1, 0, 2, 2, 34, 6, 0, 126
and the code:
List<byte> lastBuf = new List<byte>();
List<byte[]> Extract(byte[] data, byte delim)
{
List<byte[]> result = new List<byte[]>();
for (int i = 0; i < data.Length; i++)
{
if (lastBuf.Count > 0)
{
if(data[i] == delim)
{
result.Add(lastBuf.ToArray());
lastBuf.Clear();
}
else
{
lastBuf.Add(data[i]);
}
}
else
{
if(data[i] != 126)
{
lastBuf.Add(data[i]);
}
}
}
return result;
}
result :

Music major scale converter

i am trying to create music major scale converter.
Dose anyone have info how do to it
so far i have
rootNote is scale base note like cMajor or gMajor
note is note that i want to convert into major scale 0-126
if i insert rootNote 60 and note 60 the right return would be 0,
if i insert rootNote 60 and note 61 the right return would be 2,
if i insert rootNote 60 and note 62 the right return would be 4,
if i insert rootNote 60 and note 63 the right return would be 5,
if i insert rootNote 61 and note 60 the right return would be 0,
if i insert rootNote 61 and note 61 the right return would be 1,
if i insert rootNote 61 and note 62 the right return would be 3,
if i insert rootNote 61 and note 63 the right return would be 5,
ok i have this other one and it seems to work
i want to map my sequence out put in major scale
but is there some kind of formula what can i use?
.
public int getINMajorScale(int note, int rootNote)
{
List<int> majorScale = new List<int>();
//int bNote = (int)_bNote.CurrentValue;
int bNoteMpl = bNote / 12;
bNote = 12 + (bNote - (12 * bNoteMpl)) - 7;
majorScale.Add(bNote + (12 * bNoteMpl));
int tBnote = bNote;
int res = 0;
for (int i = bNote; i < bNote + 6; i++)
{
//algorytm
res = tBnote + 7;
int mod = 0;
if (res >= 12)
{
mod = res / 12;
res = res - 12 * mod;
}
tBnote = res;
majorScale.Add(res + (bNoteMpl * 12));
}
majorScale.Sort();
int modNuller = 0;
if (nmr >= 7)
{
modNuller = nmr / 7;
nmr = nmr - 7 * modNuller;
}
return (majorScale[nmr] + (modNuller *12));
}
but it's obviously faulty.
Problems with the code as it stands:
modScaling does nothing more than rootNote % 12 as you always pass in 0 and 11
You define mNote but never use it
i is never used in the for loop and so each of the 5 iterations prints the same thing.
OK, lets translate your examples into actual notes to make it easier to understand (numbers presumably correspond to MIDI notes):
rootNote = 60 (C), note = 60 (C) - output 0
rootNote = 60 (C), note = 61 (C#) - output 2
rootNote = 60 (C), note = 62 (D) - output 4
rootNote = 60 (C), note = 63 (D#) - output 5
rootNote = 61 (C#), note = 60 (C) - output 0
rootNote = 61 (C#), note = 61 (C#) - output 1
rootNote = 61 (C#), note = 62 (D) - output 3
rootNote = 61 (C#), note = 63 (D#) - output 5
I might be being really dense but I'm afraid I can't see the pattern there.
A Major scale is of course made up of the sequence Tone, Tone, Semi-tone, Tone, Tone, Tone, Semi-tone, but how does that map to your outputs?
Given your input-outputs, I think I know what you are looking for.
determine steps = note - rootNote
determine interval = number of semi-tones between rootNote and the note steps up the scale
determine phase = rootNote - 60
This algorithm provides accurate results:
static int getINMajorScale(int note, int rootNote)
{
if (note < rootNote) return 0;
var scale = new[] { 2, 2, 1, 2, 2, 2, 1 };
var phase = rootNote - 60;
var steps = note - rootNote;
var interval = steps == 0
? 0 : Enumerable.Range(0, steps).Sum(step => scale[step % scale.Length]);
var number = phase + interval;
return number;
}
yielding:
static void Main(string[] args)
{
//rootNote = 60(C), note = 60(C) - output 0
//rootNote = 60(C), note = 61(C#) - output 2
//rootNote = 60(C), note = 62(D) - output 4
//rootNote = 60(C), note = 63(D#) - output 5
//rootNote = 61(C#), note = 60 (C) - output 0
//rootNote = 61(C#), note = 61 (C#) - output 1
//rootNote = 61(C#), note = 62 (D) - output 3
//rootNote = 61(C#), note = 63 (D#) - output 5
Console.WriteLine(getINMajorScale(60, 60)); // 0
Console.WriteLine(getINMajorScale(61, 60)); // 2
Console.WriteLine(getINMajorScale(62, 60)); // 4
Console.WriteLine(getINMajorScale(63, 60)); // 5
Console.WriteLine(getINMajorScale(60, 61)); // 0
Console.WriteLine(getINMajorScale(61, 61)); // 1
Console.WriteLine(getINMajorScale(62, 61)); // 3
Console.WriteLine(getINMajorScale(63, 61)); // 5
Console.ReadKey();
}

Categories