Text to Binary JS - javascript

I'm working on a piece of code to turn text to binary. First, I turn the text to decimal, then the decimal to binary. The problem I'm getting, is in the 'decimalToBinary' function, it is telling me "Uncaught TypeError: Cannot read property 'toString' of undefined", could someone explain what's wrong?
function start() {
var text = readLine("Input the string you would like to encode: ");
var binary = textToBinary(text);
println(binary);
}
function textToBinary(text) {
var toASCII = [];
var toBINARY = [];
text.toUpperCase();
for (var i = 0; i < text.length; i++) {
var ASCII_CODE = text.charCodeAt(i);
toASCII.push(ASCII_CODE);
}
for (var j = 0; j < toASCII.length; i++) {
var arrnum = toASCII[i]
var final = decimalToBinary(arrnum);
toBINARY.push(final);
}
return toBINARY;
}
function decimalToBinary(decimalValue) {
var binaryBase = 2;
var numBitsDesired = 8;
var binaryValue = decimalValue.toString(binaryBase);
while (binaryValue.length < numBitsDesired) {
binaryValue = "0" + binaryValue;
}
return binaryValue;
}

You've some typos in your code:
function textToBinary(text){
var toASCII = [];
var toBINARY = [];
text.toUpperCase();
for(var i = 0 ; i < text.length ; i++){
var ASCII_CODE = text.charCodeAt(i);
toASCII.push(ASCII_CODE);
}
for(var j = 0 ; j < toASCII.length ; i++){ // <- This should be j++ instead of i++
var arrnum = toASCII[i] // <- Same here; j instead of i (i is off limits).
var final = decimalToBinary(arrnum);
toBINARY.push(final);
}
return toBINARY;
}
By accessing an array with an invalid index (out of bounds), you're getting an undefined value.

Related

Facing issue while reading stdin in node

I just registered in HackerEarth and trying to solve the first basic problem: Monk and rotation. When I am running the code by entering single input it works fine but when I submit the solution it does not work.
https://www.hackerearth.com/practice/codemonk/
It seems I am reading the input incorrectly
Can someone please help.
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input += input; // Reading input from STDIN
});
process.stdin.on("end", function () {
let lines = stdin_input.split('\n');
let len = lines.length;
let inputArr = [];
const numberTestCase = lines[0]
const output = new Array()
for (i = 1; i < lines.length; i++) {
let lineInput = lines[i].split(' ');
let noOfElement = 0;
let stepRotation = 0;
let skipLineUpto = 0;
let inputData = false;
if (lineInput.length === 2) {
inputData = true;
noOfElement = lineInput[0]
stepRotation = lineInput[1]
skipLineUpto = parseInt(i) + 2;
}
if (inputData) {
let stringOfArray = lines[i + 1];
let arrayData = stringOfArray.split(' ');
let mod = 0
mod = stepRotation % noOfElement;
if (mod != 0) {
let unReversedArray = arrayData.splice(-mod);
let ff = unReversedArray.concat(arrayData)
inputArr.push(ff.join(' '))
} else {
let ff = arrayData
console.log(ff.join(' '))
inputArr.push(ff.join(' '))
}
}
}
main(inputArr)
});
function main(input) {
process.stdout.write(input.join("\n")); // Writing output to STDOUT
}
When you submit you can see why your code is not valid.
Your solution is for when scenarios where input is 3 lines (1 test case), like in their example, but you can see their test cases where they have inputs of multiple lines (T test cases).
Without any prototype method something like this would work (not working because time exceeded):
let lines = stdin_input.split('\n');
let loops = lines[0];
for(i = 1; i < lines.length; i+=2) {
let steps = lines[i].split(' ')[1];
let arr = lines[i+1].split(' ');
for (j = 0; j < steps; j++) {
var x = arr[arr.length-1], i;
for (k = arr.length-1; k > 0; k--) {
arr[k] = arr[k-1];
}
arr[0] = x;
}
main(arr);
}
With pop() and unshift() only one test case is failing due to time exceeded but should get you close to the final solution:
let lines = stdin_input.split('\n');
let loops = lines[0];
for(i = 1; i < lines.length; i+=2) {
let steps = lines[i].split(' ')[1];
let arr = lines[i+1].split(' ');
for (j = 0; j < steps; j++) {
arr.unshift(arr.pop());
}
main(arr);
}

how to fill in the value in the array

i have code like this in actionscript3,
var map: Array = [
[[0,1,0],[0,1,0]],
[[0,1,0], [0,1,0]]];
var nom1: int = 0;
var nom2: int = 0;
var nom3: int = 1;
var nom4: int = 18;
stage.addEventListener (Event.ENTER_FRAME, beff);
function beff (e: Event): void
{
map[nom1][nom2][nom3] = nom4
}
stage.addEventListener (MouseEvent.CLICK, brut);
function brut(e: MouseEvent):void
{
trace (map)
}
when run, it gets an error in its output
what I want is to fill in each "1" value and not remove the "[" or "]" sign
so when var nom1, var nom2 are changed
Then the output is
[[[0,18,0],[0,18,0]],
[[0,18,0],[0,18,0]]]
please helps for those who can solve this problem
If what you want to achieve is to replace every 1 by 18 in this nested array, you could try :
for (var i = 0; i < map.length; i++) {
var secondLevel = map[i];
for (var j = 0; j < secondLevel.length; j++) {
var thirdLevel = secondLevel[j];
for (var k = 0; k < thirdLevel.length; k++) {
if (thirdLevel[k] === 1) {
thirdLevel[k] = 18;
}
}
}
}
Note that, this would only work for nested arrays with 3 levels of depth

Last element of the array is always NaN even though I used Number() function

Kindly help me investigate my function below since I'm stuck and still having a hard time figuring it out.
All is well until it reaches the last column on the nested FOR loop. The last column of each row's values are only "0". However, I used the Number() function to make the cell values(i.e. "0") a number but I keep on getting NaN for the last element of the SUM & COUNT arrays.
colCount = 326 while rowCount = 374.
sum.length and count.length should really be ONLY 325 since the headers are unnecessary and the first column is just composed of time stamps. I was able to .push(0) successfully until the nested FOR loop changed the result of the last element to NaN.
function processDataToDictionary(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var csvArray = [];
for (let i = 0; i < allTextLines.length - 1; i++) {
var row = allTextLines[i].split(',');
csvArray.push(row);
}
var colCount = csvArray[0].length;
var rowCount = csvArray.length;
//Arrays of values
var count = [];
var sum = [];
var average = [];
var headers = [];
for (let i = 1; i < colCount; i++) {
var current = csvArray[0][i].replace(/"/g, '');
sum.push(0);
count.push(0);
headers[i] = current;
}
for (let i = 1; i < rowCount; i++) {
for (let j = 1; j < colCount; j++) {
// Remove the quotes from your array
current = csvArray[i][j].replace(/"/g, '');
// Added the Method IsNullOrWhiteSpace
if (!isNullOrWhitespace(current)) {
// Parse as double not int to account for dec. values
sum[j] += Number(current);
count[j]++;
}
}
}
for (let i = 0; i < colCount; i++) {
average.push((sum[i] + 0.0) / count[i]);
}
for (let i = 1; i < colCount; i++) {
// create an empty array
dictionary[headers[i]] = average[i];
}
return dictionary;
}
function isNullOrWhitespace(input) {
if (input == " ") {
return true;
} else {
return false;
}
}
This gives you a dictionary (Object) with the columns names as keys and numbers that appear to be the correct averages as values. But one must still check whether there is a fault in the logic somewhere and the averages are not correct in fact.
function processDataToDictionary(csv) {
function isNullOrWhitespace(input) {
if (input === " ") {
return true;
} else if (input === null) {
return true;
//} else if (input === undefined) {
//return true;
} else {
return false;
}
}
var allTextLines = csv.split(/\r\n|\n/);
var csvArray = [];
for (let i = 0; i < allTextLines.length - 1; i++) {
var row = allTextLines[i].split(',');
csvArray.push(row);
}
var colCount = csvArray[0].length;
var rowCount = csvArray.length;
//Arrays of values
var count = [];
var sum = [];
var average = [];
var headers = [];
for (let i = 1; i < colCount; i++) {
var current = csvArray[0][i].replace(/"/g, '');
sum.push(0);
count.push(0);
headers[i] = current;
}
/**** I added these two lines ****/
sum.push(0);
count.push(0);
for (let i = 1; i < rowCount; i++) {
for (let j = 1; j < colCount ; j++) {
// Remove the quotes from your array
current = csvArray[i][j].replace(/"/g, '');
// Added the Method IsNullOrWhiteSpace
if (!isNullOrWhitespace(current)) {
// Parse as double not int to account for dec. values
sum[j] += Number(current);
count[j]++;
}
}
}
for (let i = 0; i < colCount; i++) {
average.push((sum[i] + 0.0) / count[i]);
}
// I added this line:
dictionary = {};
for (let i = 1; i < colCount; i++) {
dictionary[headers[i]] = average[i];
}
return dictionary;
}
Let me know if this works out for you. You can loop through the values with: for (let key in dictionary) {console.log("key: " + key + " , value: " + dictionary[key]);} . Regards!

I'm having trouble adding these elements of my array together. the dash seems to inhibit the addition of each variable

I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});

Javascript create multidimensional array

I try to create a 4-dimensional array. I fill it dynamically and use content of it in another function. But the content is empty. Is there error below code?
var datas = []; // day number of a week
for(var i = 0; i < 7; i++) {
var size = 24*60/timeInterval;
datas[i] = [];
for(var j = 0; j < size; j++) {
var size2 = allCoords.length / 2;
datas[i][j] = [];
for(var k = 0; k < size2; k++) {
datas[i][j][k] = [];
}
}
}
I test below example :
function foo1()
{
datas[0][0][0].push(10);
}
function foo2()
{
document.getElementByID('result').innerHTML = datas[0][0][0];
}
I see only ,,,,,,,.
I think the principal problem is that you're getting the element where you want to show your result badly using getElementByID instead of getElementById. Also make sure that your element has innerHTML property to write the result, or alternatively use value.
I write the follow example using <textArea id="result"></textArea> and generating a button which calls foo1();foo2(); onClick an it works for me.
In the sample I use an random value for timeInterval and allCoords.length.
Note also that you want a 4-dimensional array however you're creating a 3-dimensional.
var timeInterval = 60;
var allCoords = { length : 1};
var datas = []; // day number of a week
for(var i = 0; i < 7; i++) {
var size = 24*60/timeInterval;
datas[i] = [];
for(var j = 0; j < size; j++) {
var size2 = allCoords.length / 2;
datas[i][j] = [];
for(var k = 0; k < size2; k++) {
datas[i][j][k] = [];
}
}
}
function foo1()
{
datas[0][0][0].push(10);
}
function foo2()
{
document.getElementById('result').value = datas[0][0][0];
}
<textArea id="result"></textArea>
<input type="button" value="foo" onclick="foo1();foo2();"/>
Hope this helps,

Categories