I'm having two CSV files where the first one looks like this:
ID Time PositionX PositionY
1 23
2 26
3 56
And another one that looks like this:
ID Time PositionX PositionY
25 2.5 5.5
28 4.1 5.6
35 4.8 6.2
66 5.5 7.5
The result that I want is:
ID Time PositionX PositionY
1 25(or 23) 2.5 5.5
2 28(or 26) 4.1 5.6
3 35(or 56) 4.8 6.2
So basically, I'm trying to merge two different files with different amount of data. But to combine them I need a key, the problem is that the key cannot be exactly the same for both of the data.
So I need to get Line by Line from one data set, see it's time, and see with the other dataset if there's a value close to this. If yes then merge them.
That's why I putted "25(or 23)" because the time is in milliseconds so I need to be sure that the line of the first dataset doesn't match with 28 but 25.
The final Key can be either 23 (from the first dataset) or 25 (from the second dataset). It doesn't matter as long as the line chosen is the closest to the value.
So I found out how to do it:
First I get the time of Dataset1:
String[] File1Rows = File.ReadAllLines(secondSensor.MyFile);
int number = Convert.ToInt32(File1Rows[1].Split(';')[0]);
Then create a list of strings made out of Dataset2:
String[] AccelerometerRows = File.ReadAllLines(fifthSensor.MyFile);
List<string> AccelerometterTimes = new List<string>(AccelerometerRows);
Then I take only the times in Dataset2 and put them into a list of strings
List<int> AccelerometterTimesList = new List<int>();
for (int i = 1; i < AccelerometterTimes.Count; i++)
{
var x = AccelerometerRows[i].Split(';')[0];
Console.WriteLine(x);
AccelerometterTimesList.Add(Convert.ToInt32(x));
}
Use a little bit of LinQ to get the closest value with O(n) complexity:
int closest = AccelerometterTimesList.Aggregate((x, y) => Math.Abs(x - number) < Math.Abs(y - number) ? x : y);
Then print it out:
Console.WriteLine("number: "+number);
Console.WriteLine("closest "+closest);
After this was found, now we use closest to get the line of Dataset2 that we need to get it's position. We take then the position, put them in the line of number from Dataset1.
Related
Prime Number Generator Code
Do know that this question should be quite basic but i have spent hours trying to figure out why my code is stuck in the loop as below. Have added a Console.WriteLine($"{counttemp} , {count1} "); in the if loop to check the 2 numbers and seems like it is not breaking out of the if condition when the condition is true
this is the console output for the writeline in the if loop
5 , 5
6 , 2
7 , 7
8 , 2
9 , 3
10 , 2
11 , 11
12 , 2
13 , 13
14 , 2
15 , 3
16 , 2
17 , 17
18 , 2
19 , 19
Problematic Loop??
for (count1 = 2; count1 <= counttemp ; ++count1)
{
if(counttemp % count1 == 0)
{
Console.WriteLine($"{counttemp} , {count1} ");
Console.ReadKey();
primetest1 = 0;
break;
}
}
full code sequence
static void Main(string[] args)
{
int prime1 = 10000, count1, primetest1, counttemp;
for (counttemp = 5; counttemp <= prime1; counttemp++)
{
primetest1 = 1;
for (count1 = 2; count1 <= counttemp ; ++count1)
{
if(counttemp % count1 == 0)
{
Console.WriteLine($"{counttemp} , {count1} ");
Console.ReadKey();
primetest1 = 0;
break;
}
}
if (primetest1 == 1)
{
Console.Write($"{counttemp}");
}
}
}
You're almost there. The problem is that you're checking if your candidate number is a prime by getting the remainder when divided by each number up to and including the number itself.
I think you'll find that N is a factor of N for all values of N. To fix this, you should only be checking up to but excluding the number.
And, as an aside, you don't really need to check all the way up to N - 1. You only need to go to the square root of N, adjusted up to the nearest integer. That's because, if it has a factor above the square root, you would already have found a factor below it.
Consider 24 as an example. It has 6, 8, and 12 as factors above the square root, but the matching values below the square root are 4, 3, and 2 respectively.
And there's a another trick you can use by realising that if a number is a multiple of a non-prime, it's also a multiple of every prime factor of that non-prime. In other words, every multiple of 12 is also a multiple of 2 and 3.
So you only need to check prime numbers up to the square root, to see if there's a factor. And prime numbers, other than two or three, are guaranteed to be of the form 6x-1 or 6x+1, so it's quite easy to filter out a large chunk of candidates very quickly, by checking only for those values.
In other words, check two and three as special cases. Then start at 5 and alternately add 2 and 4: 5, 7, 11, 13, 17, 19, .... Not every number in that set is prime (e.g, 25) every prime is guaranteed to be in that set.
You can check out an earlier answer of mine for more detail on why this is so, and how to do this sequence efficiently.
I have an empty 2D array called stockGains which I am trying to append with values of gains (the value of nextPrice/currentPrice) but I cannot seem to find an appropriate operator or method in C# to be able to append to my 2D array and complete my loop? Currently, I have incorrectly used .Add to give an example. The 2D array stockGains should be dynamically sized.
double[,] stockGains = {};
foreach (double currentPrice in pricesMonth1AsList){
// divide the nextPrice by currentPrice
double gains = ((currentPrice+1)/currentPrice);
// append the result to stockGains
stockGains.Add(gains);
// do this on repeat for every day of the month until the end of pricesMonth1Aslist
}
I have stored historical price data to be iterated over as a List<double> called pricesMonth1AsList which has each currentPrice stored as doubles sequentially from day 1 to day 30 (you can consider the index position of the list to be (day of the month - 1). nextPrice is the value of price the day after (which i have represented as currentPrice+1 in index position) example of the sample data is here:
20.35, 30.5, 40.2, 50 represents Day 1 [0], Day 2 [1], Day 3 [2], Day 4 [3]
etc
For example the first gain to be calculated would be 30.5/20.35 and then this value is to be stored as the first value in index 0 of the 2D array, the second value would be 40.2/20.35, the third would be 50/20.35 also stored in index 0 of stockGains until the last day of the month. Then repeats the process again but from day 2 onwards i.e 40.2/30.5, 50/30.5 etc gains will be stored in index 1 of stockGains.
The end goal is to find the single maximum gains value in the 2D array at the end.
I am not sure if this answers your question; and I adjusted your loop to be able to access the previous element, that's why I am using for.
I believe this will be easier with a Tuple<Tx,Ty> (this has my preference)
Create a List<> out of it, and you'll have an Add:
var pricesMonth1AsList = new List<double>()
{
0,1,2,3,4,5
};
//init
var list2D = new List<Tuple<double,double>>();
for (int i = 1; i < pricesMonth1AsList.Count; i++) {
//calculate your values
//since I did not understand the calculation,
//here's just a dummy one
var currentValue = pricesMonth1AsList[i];
var previousValue = pricesMonth1AsList[i-1];
double a = previousValue/currentValue;
double b = i;
//and add it as such
list2D.Add(new Tuple<double,double>(a,b));
}
foreach(var item in list2D)
{
Console.WriteLine($"{item.Item1} - {item.Item2}");
}
Output:
0 - 1
0.5 - 2
0.6666666666666666 - 3
0.75 - 4
0.8 - 5
If I wanted to get the nearest value to a number, but that value also has to return true on a bool called IsMultipleOf7 which returns true on numbers that are multiples of 7.
For example, I have a int x = 523. So the nearest multiple of 7 is 525, so my bool would return true 525.
How can I get that number?
This function will return the closest multiple of 7 or the number itself if it is a multiple of 7
public int GetClosestNumber(int number, out bool isMultipleOf7)
{
// if the number is a multiple of 7 isMultipleOf7 is set to true
isMultipleOf7 = number%7 == 0;
if (isMultipleOf7)
{
// if it's a multiple of 7 then the closest one is the number itself
return number;
}
// if it's not a multiple of 7 then try find the closest.
var lower = number - (number % 7);
var upper = (number + 7) - (number %7);
var diffL = Math.Abs(number - lower);
var diffU = Math.Abs(number - upper);
return diffL > diffU ? upper : lower;
}
And here's a usage example:
bool IsMultipleOf7;
// Following line will output: Closest multiple of 7 is: 525
Console.WriteLine("Closest multiple of 7 is: {0}",
GetClosestNumber(523, out IsMultipleOf7));
// Following line will output: The number itself is not a multiple of 7"
Console.WriteLine("The number itself is {0} a multiple of 7",
IsMultipleOf7 ? string.Empty: "not");
Live demo is also available here
int x = 523;
while ((int)x/7!=(decimal)x/7){
x++;
}
return x;
int x = 523;
int result = ((x / 7) + 1) * 7;
You may need a more complex formula, if your number is dividable by 7 and should stay the same number. Or maybe you have simplified your problem too much?
There are two ways I can think of. The first is the brute force method I commented about. If you start with the number x, test it. If it works, hooray! If not, try adding one to x and test. Then subtract one from x and test. Then do this with two, and three, testing up and down at the same time. Once your test returns true, you have located (one of) the closest number(s) that work. This method is a general one and will work with any test function.
Because we know you are using IsMultipleOf7 as the test, a smarter method could be possible. Imagine the time it would take if your test was instead IsMultipleOf999999999! So many numbers might have to tested before hitting the closest. Instead, some math can be used. First, compute x modulo 7 (for IsMultipleOf7), written x % 7 in C(++). This value tells you how far x is from the largest multiple of 7 LESS than x. If this value is 0, x is a multiple of 7. If the value is 1, 2 or 3, x minus the value is the closest multiple. If the value is 4, 5 or 6, x plus the difference to make 7 (7 - value) is the closest multiple.
Some pseudo-code:
x = 523
value = x modulo 7
if(value == 0):
return x
if(value < 4): // that is, less than half of 7
return x - value
otherwise
return x + (7 - value)
x=7*Math.Round(((float)x)/7.0)
^Simplest solution right there ;)
No need for all of this looping and stuff.
divide by 7, if the decimals are less than 0.5 then the nearest denominator is floored, else ceiling. Round() does that for you, then just multiply your new int by 7 to create a number evenly divisible by 7 (since it was an int being multiplied by 7). It will get the closest value above or below. No need for bool at all. Make sure you cast float onto x so that it can be divided by 7 without causing flooring with integer logic.
function [ samples,y, energies] = energy( speech, fs )
window_ms = 200;
threshold = 0.75;
window = window_ms*fs/1000;
speech = speech(1:(length(speech) - mod(length(speech),window)),1);
samples = reshape(speech,window,length(speech)/window);
energies = sqrt(sum(samples.*samples))';
vuv = energies > threshold;
y=vuv;
I have this matlab code and I need to write this code in c#. However I couldn't understand the last part of the code. Also i think speech corresponds to a data List or array according to first part of code. If it does not, please can someone explain what this code is doing. I just want to know logic. fs = 1600 or 3200;
The code takes an array representing a signal. It then breaks it into pieces according to a window of specified length, compute the energy in each segment, and finds out which segments have energy above a certain threshold.
Lets go over the code in more details:
speech = speech(1:(length(speech) - mod(length(speech),window)),1);
the above line is basically making sure that the input signal's length is a multiples of the window length. So say speech was an array of 11 values, and window length was 5, then the code would simply keep only the first 10 values (from 1 to 5*2) removing the last remaining one value.
The next line is:
samples = reshape(speech,window,length(speech)/window));
perhaps it is best explained with a quick example:
>> x = 1:20;
>> reshape(x,4,[])
ans =
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
so it reshapes the array into a matrix of "k" rows (k being the window length), and as many columns as needed to complete the array. So the first "K" values would be the first segment, the next "k" values are the second segment, and so on..
Finally the next line is computing the signal energy in each segment (in a vectorized manner).
energies = sqrt(sum(samples.*samples))';
List<int> speech = new List<int>();
int window = 0;
int length = speech.Count();
int result = length % window;
int r = length - result;
// speech = speech(1: r, 1)
This:
(length(speech) - mod(length(speech),window)
is a formula
([length of speech] - [remainder of (speech / window)])
so try
(length(speech) - (length(speech) % window))
% is the symbol equivalent to mod(..)
EDIT I should say that I assume that is what mod(..) is in your code :)
Based on my understanding of how check digits are supposed to be calculated for barcodes, namely:
0) Sum the values of all the characters at odd indexes (1, 3, etc.)
1) Multiply that sum by 3
2) Sum the values of all the characters at even indexes (o, 2, etc.)
3) Combine the two sums from steps 1 and 2
4) Calculate the check digit by subtracting the modulus 10 of the combined sum from 10
So for example, with a barcode "04900000634" the combined sum is 40*; To get the check sum, the modulus (40 % 10) == 0, and then 10 - 0 == 10.
Odd characters == 7; X3 = 21; Even characters == 19, for a combined sum of 40.
Since a check digit is a scalar value, what if the result of the check digit calculation is 10? Does one use "0" or "1"?
Here is the code I'm using (thanks to some help from here: Why does 1 + 0 + 0 + 0 + 3 == 244?); I'm assuming that the formula pseudocoded above applies regardless of the length (8 chars, 12 chars, etc.) and type (128, EAN8, EAN12, etc.) of the barcode.
private void button1_Click(object sender, EventArgs e)
{
string barcodeWithoutCzechSum = textBox1.Text.Trim();
string czechSum = GetBarcodeChecksum(barcodeWithoutCzechSum);
string barcodeWithCzechSum = string.Format("{0}{1}", barcodeWithoutCzechSum, czechSum);
label1.Text = barcodeWithCzechSum;
}
public static string GetBarcodeChecksum(string barcode)
{
int oddTotal = sumOddVals(barcode);
int oddTotalTripled = oddTotal*3;
int evenTotal = sumEvenVals(barcode);
int finalTotal = oddTotalTripled + evenTotal;
int czechSum = 10 - (finalTotal % 10);
return czechSum.ToString();
}
private static int sumEvenVals(string barcode)
{
int cumulativeVal = 0;
for (int i = 0; i < barcode.Length; i++)
{
if (i%2 == 0)
{
cumulativeVal += Convert.ToInt16(barcode[i] - '0');
}
}
return cumulativeVal;
}
private static int sumOddVals(string barcode)
{
int cumulativeVal = 0;
for (int i = 0; i < barcode.Length; i++)
{
if (i % 2 != 0)
{
cumulativeVal += Convert.ToInt16(barcode[i] - '0');
}
}
return cumulativeVal;
}
UPDATE
The calculator here: http://www.gs1us.org/resources/tools/check-digit-calculator claims that the check digit for 04900000634 is 6
How is that being arrived at?
UPDATE 2
This http://www.gs1.org/barcodes/support/check_digit_calculator
revises my understanding of the last part of the equation/formula, where it says, "Subtract the sum from nearest equal or higher multiple of ten = 60- 57 = 3 (Check Digit)"
So, in the case of 04900000634, the combined sum is 40. Based on that formula, the "nearest equal or higher multiple of ten" of 40 is 40, so 40-40=0, and I would expect that to be the check sum (not 6)...so, still confused...
UPDATE 3
I'm not understanding why yet, but mike z's comment must be correct, because when I reverse the "==" and "!=" logic in the sumOddVals() and sumEvenVals() functions, my results correspond to those generated by http://www.gs1us.org/resources/tools/check-digit-calculator
UPDATE 4
Apparently, based on http://en.wikipedia.org/wiki/European_Article_Number, the powers that be behind check digit calculations don't consider the first position to be position 0, but position 1. Confusing for developers, trained to see the first item as residing at index 0, not 1!
The check digit is always last.
Starting with the digit immediately to the left of the check digit and moving LEFT, sum each digit, applying a weight of 3 and 1 alternately.
The check digit is then the number which needs to be added to produce a result that is a multiple of 10.
This works for ALL EAN/UPC codes - UPC-E, EAN-8 (which is all valid 8-digit codes except those whoch start 0,6 or 7) UPC-A (12-digit), EAN-13, EAN-14 (sometimes call "TUN" or "Carton" codes) and SSCCs (actually 18-digit, but implemented as part of the EAN128 standard with an AI of '00', misleading some into believing they're 20-digit codes)
When UPC-E was introduced, the original scheme was [language][company][product][check]. 0,6 and 7 were assigned to English and the remainder unassigned. [company] and [product] were variable-length with total 6 digits; short company numbers for companies with many products, long for companies with few products.
EAN used the remainder of the numbers, but assigned [country][company][product][check] where country was 2-digit.
That system soon ran out of puff, but is still occasionally assigned for very small products - and the original products that had numbers before UPC-A/EAN-13 was introduced.
UPC-A used the same schema as UPC-E, but lost the reference to 'language'. 0,6 and 7 were assigned to US/Canada. The company+product was extended to 10 digits.
EAN-13 extended the scheme to 13 digits, 2 for country, 10 for company+product, 1 to check. UPC-A was compatible by prefixing a leading "0".
By implementing the 13-digit scheme, US companies could track each of these codes and UPC-As did not need to be issued on products that already had an EAN-13 assigned. This was scheduled for completion about 8 years ago, but some companies still lag behind.
EAN-14s are used for carton outers. The leading digit is normall referred to as a "Trade Unit Identifier/Number" Hence the entire code is sometimes called a TUN. At first, there was an attempt to codify the leading digit (1=1doz, 2=2doz, etc.) but this was soon abandoned. Most companies use the number as a packaging level (1=cluster of individual items, 2=tray of clusters, 3=box of trays - depending on each company's preference. 9 is reserved. Not a good idea to use 0 (though some companies have) since it produces the same check-digit as the 13-digit code. I've used this for EAN128 codes bearing the batch number on non-retail goods; AI=01;EAN-14 (=EAN13 with TUN=0);AI=10;batch-number.
SSCCs are another can of worms. They're 18-digit - the first digit was originally used as a logistical descriptor, then there's the country-code, manufacturer-code and package-number with a check-digit. Originally, "3" meant an "external" pallet and "4" an "Internal" pallet, but this fell into disuse as impractical as an "Internal" pallet then has to be re-numbered if it gets sent "outside" and vice-versa.
And of course 2-digit country-codes have been supplanted by 3-digit as more countries have adopted the system.
There are different weights for different barcode formats. You have described the format for the EAN format - a 1313 weighting. Whereas UPC uses a 3131 weighting scheme. ISBN-10 uses a completely different scheme - the weights are different and the calculation is done modulo 11.
I think the reference you are using is assuming that the digits are indexed starting at 1 not 0. The effect is that you have mixed up odd and even characters. So the sum is 3 x 19 + 7 = 64 and therefore the check digit is 6 not 0. For EAN and UPC, the check digit is the value that must be added to the sum to get a number evenly divisible by 10.
Update
Your description of the check digit algorithm is accurate only for certain classes of EAN barcodes because the weights are aligned such that the last digit is always weighted by 3 (see EAN Number). Therefore, depending on the exact EAN scheme (8,12,13 or 14 digit) odd or even digits are weighted differently.
Thus the proper weights are
0 4 9 0 0 0 0 0 6 3 4
3 1 3 1 3 1 3 1 3 1 3
Giving a sum of 64 and a check digit of 6.
Based on this: http://www.gs1.org/barcodes/support/check_digit_calculator, barcode calculation formulas can either start with 1, or start with 3, based on whether the ultimate length of the barcode is even (including the checksum val) or add. If the total number of chars, including the checksum, is even, the 1st digit has a weight of three; otherwise (total char count is odd), the 1st digit has a weight of 1. In either case, 3s and 1s alternate, as "13131313..." or "31313131..."
But they always seem to end with a weight of 3; so, it shouldn't matter how long the barcode is, or whether it is odd or even. Simply calculate the value "backwards," assuming the last digit has a weight of 3; HOWEVER, whether the barcode is of even or odd length, that is to say, whether the last digit and those that alternate with it are even or odd makes all the difference in the world, so that has to be noted, too. The "inside" ordinals begin with the penultimate character in the barcode, and skip one backwards; the "outside" ordinals are the last one and then every other one. Anyway, here is the code which, AFAIK, should work to generate and validate/verify check digits for all barcode types:
private void button1_Click(object sender, EventArgs e)
{
string barcodeWithoutCheckSum = textBox1.Text.Trim();
string checkSum = GetBarcodeChecksum(barcodeWithoutCheckSum);
string barcodeWithCheckSum = string.Format("{0}{1}", barcodeWithoutCheckSum, checkSum);
label1.Text = barcodeWithCheckSum;
textBox1.Focus();
}
public static string GetBarcodeChecksum(string barcode)
{
int oddTotal;
int oddTotalTripled;
int evenTotal;
// Which positions are odd or even depend on the length of the barcode,
// or more specifically, whether its length is odd or even, so:
if (isStringOfEvenLen(barcode))
{
oddTotal = sumInsideOrdinals(barcode);
oddTotalTripled = oddTotal * 3;
evenTotal = sumOutsideOrdinals(barcode);
}
else
{
oddTotal = sumOutsideOrdinals(barcode);
oddTotalTripled = oddTotal * 3;
evenTotal = sumInsideOrdinals(barcode);
}
int finalTotal = oddTotalTripled + evenTotal;
int modVal = finalTotal%10;
int checkSum = 10 - modVal;
if (checkSum == 10)
{
return "0";
}
return checkSum.ToString();
}
private static bool isStringOfEvenLen(string barcode)
{
return (barcode.Length % 2 == 0);
}
// "EvenOrdinals" instead of "EvenVals" because values at index 0,2,4,etc. are seen by the
// checkdigitmeisters as First, Third, Fifth, ... (etc.), not Zeroeth, Second, Fourth
private static int sumInsideOrdinals(string barcode)
{
int cumulativeVal = 0;
for (int i = barcode.Length-1; i > -1; i--)
{
if (i % 2 != 0)
{
cumulativeVal += Convert.ToInt16(barcode[i] - '0');
}
}
return cumulativeVal;
}
// "OddOrdinals" instead of "OddVals" because values at index 1,3,5,etc. are seen by the
// checkdigitmeisters as Second, Fourth, Sixth, ..., not First, Third, Fifth, ...
private static int sumOutsideOrdinals(string barcode)
{
int cumulativeVal = 0;
for (int i = barcode.Length - 1; i > -1; i--)
{
if (i % 2 == 0)
{
cumulativeVal += Convert.ToInt16(barcode[i] - '0');
}
}
return cumulativeVal;
}
UPDATE
With the above code, it is easy enough to add a function to verify that a barcode (with appended checkdigit) is valid:
private static bool isValidBarcodeWithCheckDigit(string barcodeWithCheckDigit)
{
string barcodeSansCheckDigit = barcodeWithCheckDigit.Substring(0, barcodeWithCheckDigit.Length - 1);
string checkDigit = barcodeWithCheckDigit.Substring(barcodeWithCheckDigit.Length - 1, 1);
return GetBarcodeChecksum(barcodeSansCheckDigit) == checkDigit;
}