I'm working on a simple cipher algorithm and I'm trying to figure out how to stop the if statement at character 122 (z) and start back at char 97 (a) once the character count exceeds 122. This is what I have so far and have looked around on MDN and W3 schools and haven't come up with anything.
enter code here
function simpleCipher(str) {
var newString = [];
for (var i = 0; i < str.length; i ++) {
if (str.charCodeAt(i) > 97 || str.charCodeAt(i) < 122) {
var convertString = String.fromCharCode(str.charCodeAt(i) + 4);
var powerString = newString.push(convertString);
} else {
return;
}
}
return newString.join('');
}
Use modular arithmetic.
var aPos = 97;
var zPos = 122;
var charsCount = zPos - aPos + 1;
...
if (aPos <= str.charCodeAt(i) && str.charCodeAt(i) <= zPos) { // probably you want && here
var charNumber = str.charCodeAt(i) - aPos;
var charNumberEncoded = (charNumber + 4) % charsCount;
var convertString = String.fromCharCode(aPos + charNumberEncoded);
var powerString = newString.push(convertString);
}
It is considered a good practice to give constants names and not use numbers in the code. Such numbers often referenced as magic numbers and make it harder to read the code.
Related
Currently i am doing a challenge in codewars on Balanced numbers and i wrote the code in dart and it successfully completed 100 test cases but for long numbers it is not working properly...So i think that it need some conditions for this long numbers:
String balancedNum(numb) {
// your code here
var numb1 = numb.toString();
List a = numb1.split("");
var left_sum = 0;
var right_sum = 0;
for (var i = 0; i <= a.length / 2; i++) {
left_sum += int.parse(a[i]);
}
List<String> b = a.reversed.toList();
//print(b);
for (var i = 0; i < b.length / 2; i++) {
right_sum += int.parse(b[i]);
}
//print(right_sum);
if (left_sum == right_sum) {
return 'Balanced';
} else {
return 'Not Balanced';
}
}
link to the challenge:https://www.codewars.com/kata/balanced-number-special-numbers-series-number-1/train/dart
The compiler verdict for the code is wrong answer because of a simple logical error.
This is because the length of the list has not been calculated correctly
Kindly have a look at the corrected code below, which passes all the 110 test on the platform:
String balancedNum(numb) {
// your code here
var numb1 = numb.toString();
List a = numb1.split("");
var left_sum = 0;
var right_sum = 0;
double d = ((a.length-1) / 2);
int len = d.floor();
print(len);
for (var i = 0; i < len; i++) {
left_sum += int.parse(a[i]);
}
List<String> b = a.reversed.toList();
print(b);
for (var i = 0; i < len; i++) {
right_sum += int.parse(b[i]);
}
print(left_sum);
print(right_sum);
if (left_sum == right_sum) {
return 'Balanced';
} else {
return 'Not Balanced';
}
}
Your problem is not about "long numbers" since you code also fails for the test case using the number 13.
You properly did not read the following rules:
If the number has an odd number of digits then there is only one middle digit, e.g. 92645 has middle digit 6; otherwise, there are two middle digits , e.g. 1301 has middle digits 3 and 0
The middle digit(s) should not be considered when determining whether a number is balanced or not, e.g 413023 is a balanced number because the left sum and right sum are both 5.
So you need to test if the number are even or uneven since we need to use that information to know how many digits we should use in the sum on each side.
I have done that in the following implementation:
String balancedNum(int numb) {
final numb1 = numb.toString();
final a = numb1.split("");
var split = (a.length / 2).floor();
if (a.length % 2 == 0) {
split--; // the number is even
}
var left_sum = 0;
var right_sum = 0;
for (var i = 0; i < split; i++) {
print(a[i]);
left_sum += int.parse(a[i]);
}
final b = a.reversed.toList();
for (var i = 0; i < split; i++) {
right_sum += int.parse(b[i]);
}
if (left_sum == right_sum) {
return 'Balanced';
} else {
return 'Not Balanced';
}
}
For this question with illustrative purpose I will write Javascript code, but that's just an illustration, the question is language-agnostic.
I need to write a function which takes a barcode text (not the image) as an input and returns the ISBN as output. ISBN can be of 10 digits (older books) or 13 digits (newer books). We also know that the last digit of an ISBN is a checksum, which is computed differently if the ISBN is 10 digits long and differently if the ISBN is 13 digits long.
Assuming that input is a string, we can validate whether it is a valid ISBN, like:
function isValidISBN10(input) {
if (input.length !== 10) return false;
var sum = 0;
var p = 10;
for (var index = 0; index < 10; index++) {
sum += ((input[index] === 'X') ? 10 : input[index]) * (p--);
}
return sum % 11 === 0;
}
and ISBN13 can be validated like:
function isValidISBN13(input) {
if (input.length !== 13) return false;
var sum = 0;
var p = 3;
for (var index = 0; index < 13; index++) {
sum += input[index] * (p = (p + 2) % 4);
}
return sum % 10 === 0;
}
Checking a valid ISBN is:
function isValidISBN(input) {
return isValidISBN10(input) || isValidISBN13(input);
}
As we can see, the last digit of an ISBN is the number we should add in order to make sure the result is divisible by 11 (in the case of ISBN10) and 10 (in the case of ISBN13). The 'X' in the case of ISBN10 represents a number of 10 in 11-base.
As far as I understand these articles:
https://www.barcodefaq.com/1d/isbn/
https://isbn-information.com/isbn-barcode.html
barcodes will contain the digits of ISBNs, except its last digit, the example the first article gives is
ISBN = 09767736X
Barcode = 9780976773665
What confuses me is the number of 51050 on this picture
I wonder whether it is part of the barcode or not. If we consider it not to be a barcode, then converting a barcode to an ISBN would be trivial:
function convertBarcodeIntoISBN(input) {
var isbn = {isbn13: input};
if (input.startsWith("978")) {
var isbn10 = input.substring(3);
var checksum = 0;
var p = 10;
for (var index = 0; index < 9; index++) {
checksum += isbn10[index] * (p--);
}
checksum = 11 - (checksum % 11);
if (checksum === 10) checksum = 'X';
isbn10 += checksum;
isbn.isbn10 = isbn10;
}
return isbn;
}
But if we consider 51050 to be part of the barcode, then we will need to mine the ISBN from the barcode, however, in this case I am not sure how should I operate. The best I can pull from the top of my mind is:
function getLastISBNDigit(input) {
if ((input.length != 10) && (input.length != 13)) return;
var is10 = (input.length === 10);
var sum = 0;
var p = (is10 ? 11 : 3);
for (var index = 0; index < input.length - 1; index++) {
sum += ((input[index] === 'X') ? 10 : input[index]) * (p = (is10 ? (p - 1) : ((p + 2) % 4)));
}
var moduloClass = (is10 ? 11 : 10);
var result = (moduloClass - (sum % moduloClass)) % moduloClass;
return ((result === 10) ? 'X' : result);
}
function getISBN(input) {
var isbn = {};
if (input.length > 13) return getISBN(input.substring(0, 13));
if (input.length === 10) {
if (isValidISBN(input)) {
isbn.isbn10 = input;
isbn.isbn13 = "978" + input;
isbn.isbn13 = isbn.isbn13.substring(0, 12) + getLastISBNDigit(isbn.isbn13);
}
} else if (input.length === 13) {
if (isValidISBN(input)) {
isbn.isbn13 = input;
if (input.startsWith("978")) {
isbn.isbn10 = input.substring(3);
isbn.isbn10 = isbn.isbn10.substring(0, 9) + getLastISBNDigit(isbn.isbn10);
}
} else if (input.startsWith("978")) {
return getISBN(input.substring(3));
}
}
return isbn;
}
This is how I think barcodes should be converted into ISBN and ISBN13 values. Am I right with my reasoning?
The second part is the human-readable price (from this slide):
Hence, the first part of your consideration makes sense and 51050 is not part of the barcode!
The price of the product is 10.50$.
I have a little routine that makes up a cumulative XOR hash. It's as if it is a savings account which gets bigger, cumulatively daily.. but in this sense we're saying the answer is being generated cumulatively and the key is always present.
I have taken a string of chars
pseudo code:
char H[10] = { "ABCDEFGHI", "\0" };
and I used 9 32-bit numeric keys to hash them in XOR encryption.
I did it like this:
for (i;i<10;i++)
bitset<32> K ^= H[i] ^ NUMKEY[i];
Now this makes it impervious without the calculus plotting I did (see what I did there?) So K is an accumulation of calculus points, which are completely predictable according to calculus.
as far as I know, to undo it, I do
for (i;i<10;i++) {
X=0;
X ^= K ^ NUMKEY[i];
}
Is there other math involved? I think I have to take that X and do a little K - X to find the true derivative.
Here's the current routine I have for it. But I'm not getting what I'm looking for.
for_each (std::istreambuf_iterator<char>(in), \
std::istreambuf_iterator<char>(), \
[&] (long x) {
t=s_nop(t,0);
cred.push_back(t);
alpha = static_cast<long>(cred[size]);
delta = static_cast<long>(x);
lambda ^= (alpha ^ delta);
size++;
});
for (;i<bn;i++) {
alpha = static_cast<unsigned long>(cred[bn-1-i]);
int m = lambda.to_ulong(), n = alpha.to_ulong();
long hash1 = abs((m-n-1)%256-1);
delta = static_cast<unsigned long>(hash1);
btrace.push_back(hash1);
cout << hash1 << " ";
}
Please have a safe and Merry Christmas. Thank you in advance!
I think what you might really want is a one time pad. (the snippet is javascript as pseudocode moving in that direction)
//ignore these top 3 functions (they're just for printing output)
function appendLine(text, target, space, color) {
var line = document.createElement("div");
line.style.border = "1px solid " + color;
line.style.padding = line.style.margin = space;
line.style["font-family"] = "monospace";
line.appendChild(document.createTextNode(text));
target.appendChild(line);
return line;
}
function makeSection(title) {
var d = appendLine(title, document.body, "5px", "#dddddd");
var results = document.createElement("div");
d.appendChild(results);
return function(result) {
appendLine(result, results, "2px", "#eeeeee");
};
}
function toHex(arr) {
return arr.map(function(n){
var h = (n >>> 0).toString(16).toUpperCase();
while(h.length < 8) h = "0" + h;
return h;
}).join(",");
}
//your message
var H = "ABCDEFGHI".split("").map(function(c){return c.charCodeAt(0)});
//your secret encoding key
var NUMKEY = Array.apply(null, Array(9)).map(function(){return Math.random() * Math.pow(2, 32)});
//what you're doing
(function() {
var section = makeSection("what you're doing:");
section("ABCDEFGHI as array of 32bit numbers: " + toHex(H));
section("NUMKEY: " + toHex(NUMKEY));
var K = 0;
for (var i = 0; i < 10; i++) {
K ^= H[i] ^ NUMKEY[i];
}
section("K: " + toHex([K]));
var X = 0;
for (var i = 0; i < 10; i++) {
X ^= K ^ NUMKEY[i];
}
section("X: " + toHex([X]));
})();
//what you're trying to do
(function() {
var section = makeSection("what you're trying to do:");
section("ABCDEFGHI as array of 32bit numbers: " + toHex(H));
section("NUMKEY: " + toHex(NUMKEY));
var Hs_XORd = 0;
for (var i = 0; i < 10; i++) {
Hs_XORd ^= H[i];
}
section("H's XOR'd together: " + toHex([Hs_XORd]));
var NUMKEYs_XORd = 0;
for (var i = 0; i < H.length; i++) {
NUMKEYs_XORd ^= NUMKEY[i];
}
section("NUMKEY's XOR'd together: " + toHex([NUMKEYs_XORd]));
var K = NUMKEYs_XORd ^ Hs_XORd;
section("K: " + toHex([K]));
var X = K ^ NUMKEYs_XORd;
section("X (should be the same as H's XOR'd together): " + toHex([X]));
})();
//what I think you mean to be doing (one time pad)
(function() {
var section = makeSection("what I think you mean to be doing (one time pad):");
section("ABCDEFGHI as array of 32bit numbers: " + toHex(H));
section("NUMKEY: " + toHex(NUMKEY));
var K = [];
for (var i = 0; i < H.length; i++) {
K[i] = H[i] ^ NUMKEY[i];
}
section("K (encoded message using NUMKEY as one time pad): " + toHex(K));
var X = [];
for (var i = 0; i < K.length; i++) {
X[i] = K[i] ^ NUMKEY[i];
}
section("X (decoded message, should be the same as ABCDEFGHI): " + toHex(X));
})();
I have an algorithm trouble, I don't know how to do it and how to call it (Does it have any specific name?)
For example, if I have this sequence:
000 CASE_01
001 CASE_02
010 CASE_03
011 CASE_02
100 CASE_02
101 CASE_01
110 CASE_01
111 CASE_01
I want to convert it in something like this:
000 CASE_01
0-1 CASE_02
010 CASE_03
100 CASE_02
1-1 CASE_01
11- CASE_01
I have called it wildcard because I think is the most correct way...
They not necessarily have 3 bits, you must do it with n bits
If only I had the psudo-code I could write it to any language (Python in my way)
The code below generates all possible wildcard strings for the number of bits encountered in the input (e.g. --, -0, -1, 0-, 00, 01, 1-, 10 and 11 for 2 bits), and also creates patterns where numbers are inverted and wildcards become 1 (so wildcard 0-1 has pattern 110), and masks where numbers become 1 and wildcards become 0 (so wildcard 0-1 has mask 101).
The binary numbers in the input are then XOR-ed with the patterns and AND-ed with the masks to check whether they fit a certain wildcard. If a wildcard has the required number of matching numbers (2 ^ number_of_wildcards), it is added to the output and the matching numbers are removed from the input.
Run the code snippet to see the algorithm in action with your example input, to which I added a fourth case with larger binary numbers.
function wildcard(input) {
var output = [], cases = [], wilds = [], patts = [], masks = [];
var bits = groupCases(cases);
for (var i = 0; i <= bits; i++) wilds[i] = [];
wildStrings(bits);
convertStrings(wilds, patts, "-01", "110");
convertStrings(wilds, masks, "-01", "011");
for (var c = 0; c < cases.length; c++) {
for (var i = 0, j = Math.pow(2, bits); i <= bits; i++, j /= 2) {
for (var k = 0; k < patts[i].length; k++) {
var patt = patts[i][k];
var mask = masks[i][k];
var matches = [];
for (var d = 0; d < cases[c].nums.length; d++) {
var num = cases[c].nums[d];
if (((num ^ patt) & mask) == mask) matches.push(d);
}
if (matches.length == j) {
output.push(wilds[i][k] + " " + cases[c].id);
for (var l = j - 1; l >= 0; l--) cases[c].nums.splice(matches[l], 1);
}
}
}
}
return output;
function groupCases(cases) {
var max = 0;
for (var i = 0; i < input.length; i++) {
var num = parseInt(input[i], 2);
if (num > max) max = num;
var id = input[i].slice(input[i].indexOf(" ") + 1);
var pos = 0;
while (cases[pos] != undefined && cases[pos].id != id) ++pos;
if (cases[pos] == undefined) cases[pos] = {id: id, nums: []};
cases[pos].nums.push(num);
}
return Math.ceil(Math.log(max) / Math.log(2));
}
function wildStrings(len, wild, str) {
wild = wild || 0;
str = str || "";
for (var i = 0; i < 3; i++) {
var w = (i == 0) ? 1 : 0;
var s = str + ["-","0","1"][i];
if (len > 1) wildStrings(len - 1, wild + w, s)
else wilds[bits - wild - w].push(s);
}
}
function convertStrings(input, output, from, to) {
for (var i = 0; i < input.length; i++) {
output[i] = [];
for (var j = 0; j < input[i].length; j++) {
var str = input[i][j], s = "";
for (var k = 0; k < str.length; k++) {
s += to.charAt(from.indexOf(str.charAt(k)));
}
output[i].push(parseInt(s, 2));
}
}
}
}
var a = ["000 CASE_01", "001 CASE_02", "010 CASE_03", "1010 CASE_04",
"011 CASE_02", "100 CASE_02", "1110 CASE_04", "101 CASE_01",
"110 CASE_01", "1100 CASE_04", "1000 CASE_04", "111 CASE_01"];
var w = wildcard(a);
document.write(w.length + " wildcards:<BR><PRE>");
for (var i in w) document.write(w[i] + "<BR>");
I want to write a 3d version of a fft. (Like this:https://wiki.mozilla.org/File:Fft.png)
So I created a few bars and in an outside function, my first aproach was to set the lengthY to a value. Then I call bar.modified() to force it to be repainted.
If I now use more than 50 bars, it is horrible slow (on my 4 core CPU). I guess there's a better way to do it, right?
Source:
var elements = new Array();
create3d = function(len) {
var r = new X.renderer3D();
r.init();
if(a.length == 0){
for ( var y = 0; y < len; y++) {
var c = new X.cube();
a.push(c);
}
}
for ( var i = 0; i < len; i++) {
a[i].center = [i*2 , 0, 0];
a[i].lengthX = 1;
a[i].lengthY = 20;
a[i].lengthZ = 1;
a[i].color = [i%2,0,0];
r.add(a[i]);
}
r.render();
};
function setVal(index,val){
var element = a[index];
element.lengthY = val;
element.modified();
}
I created a JSFiddle on how to do that and it is pretty fast for 1000 cubes
http://jsfiddle.net/haehn/6fVRC/