Lossless compression run length encoding in javascript - javascript

For my assignment, I am writing the code to compress and then decompress a string through lossless compression in javascript.
For example-
Original string: heeeeelllllloo
Compressed: h1e5l6o2
Decompressed: heeeeelllllloo
This code comes out as an infinite loop, and the problem is somewhere in the compression function. Please help me find/solve the issue!
This is what I have so far:
// Read in the original text
var textToCompress = prompt("Enter the text you would like to compress: ");
runLengthEncoding(textToCompress);
function runLengthEncoding(originalText){
console.log("Original Text: " + originalText);
console.log("");
// Compress the text
console.log("COMPRESSING...");
var compressedText = compress(originalText);
console.log("Compressed: " + compressedText);
console.log("");
//Decompress the text
console.log("DECOMPRESSING...");
//var decompressedText = decompress(compressedText);
console.log("Decompressed: " + decompressedText);
console.log("");
// Make sure the compression was lossless
if(originalText == decompressedText)
{
console.log("Success! The decompressed text is the same as the original!");
}
}
// Compresses the original String by building up a new String
// with each character and how many times it repeats in a given run.
// Returns the compressed text.
function compress(original){
var result = "";
//Write your code here
for (var i = 1; i < original.length; i++){//look at each character in string
var sum = 1;
var currentChar = original.charAt(i);
//if currentchar is the first character
if (currentChar == original.charAt(0)){//isolate frist character of the string
result = currentChar;//add the currentchar to result
console.log(result);
//if currentchar is not the first character
} else if (currentChar !== original.charAt(0)) {
//if currentchar is equal to the previous character
if (currentChar == original.charAt(i-1)){
sum++;
} else {
result += sum;//add sum ot the result and reset sum to 1
sum = 1;
i = 0;
}
}
}
}
// Decompresses the compressed Run Length Encoded text back
// into the original form.
function decompress(compressedText)
{
var result = "";
for(var i = 0; i < compressedText.length; i += 2)
{
// Get the current run character
var character = compressedText.charAt(i);
// Get the run length
var runLength = parseInt(compressedText.charAt(i+1));
// Add that many repetitions of the original character to the result
for(var runIndex = 0; runIndex < runLength; runIndex++)
{
result += character;
}
}
return result;
}

First of all, don't compare the chars to find out if this char is the first one, because this would return true if the first char is repeated in the text.
The seond thing I saw, is that you set the index i to 0 every time you find a new character which leads your function to start at the beginning of the string again and will end in a deadlock.
Thats at least what I think, and I hope I could help you

Related

Split JSON every N

I'm trying to separate a json into several pieces n times depending on the size of the json and the limit of characters within a field. For example, if the json occupies 16000 characters I divide it by 4000 (which is the limit per field) and thus divide it into 4 pieces type string[0], string[1],string[2],string[3] and then print them to the screen.
I have this code but it always gives me the following error:
Error: Index and length must refer to a location within the string. Parameter name: length
var splitA = [];
function separatedFields(nCharacter, valueDeInfo) {
var limit = 4000;
var split = [];
var nfield = Math.ceil((nCharacter) / limit);
var begin = 0;
var end = 4000;
for (i = 0; i < nfield; i++) {
if (i == nfield - 1) {
split[i] = valueDeInfo.slice(begin, end);
begin = end;
end = nCharacter;
} else {
split[i] = valueDeInfo.slice(begin, end);
begin = end;
end = end + 4000;
}
}
return split;
}
splitA = separatedFields(nCharacter, valueDeInfo);
Write("ARRAY FIRST 4000: " + splitA[0]);
Example of input/output:
valueDeInfo = ['{"Status":"OK","RequestID":"e5517d4e-ee43-451a-bbe8-09f9fc714c21","Results":[{"CustomerKey":null,"Name":"Control","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":3,"DefaultValue":"1","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"CategoryID","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":8,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsSendable","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":2,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Name","ObjectID":null,"FieldType":"Text","IsPrimaryKey":true,"MaxLength":50,"Ordinal":0,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsRequired","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":10,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"infoDE3","ObjectID":null,"FieldType":"Text","IsPrimaryKey":false,"MaxLength":4000,"Ordinal":18,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Description","ObjectID":null,"FieldType":"Text","IsPrimaryKey":false,"MaxLength":4000,"Ordinal":6,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"ModifiedDate","ObjectID":null,"FieldType":"Date","IsPrimaryKey":false,"MaxLength":0,"Ordinal":7,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}']
nCharacters = valueDeinfo.length;
The correct output would be:
{"Status":"OK","RequestID":"e5517d4e-ee43-451a-bbe8-09f9fc714c21","Results":[{"CustomerKey":null,"Name":"Control","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":3,"DefaultValue":"1","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"CategoryID","ObjectID":null,"FieldType":"Number","IsPrimaryKey":false,"MaxLength":0,"Ordinal":8,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"IsSendable","ObjectID":null,"FieldType":"Boolean","IsPrimaryKey":false,"MaxLength":0,"Ordinal":2,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":false,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-01T00:00:00.000","ModifiedDate":null,"ID":0,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}, {"CustomerKey":null,"Name":"Name","ObjectID":null,"FieldType":"Text","IsPrimaryKey":true,"MaxLength":50,"Ordinal":0,"DefaultValue":"","DataExtension":null,"StorageType":"Unspecified","DataType":null,"ValueType":"xsdstring","PropertyType":"string","IsCreatable":false,"IsUpdatable":false,"IsRetrievable":false,"IsQueryable":false,"IsFilterable":false,"IsPartnerProperty":false,"IsAccountProperty":false,"PartnerMap":null,"AttributeMaps":null,"Markups":null,"Precision":0,"Scale":0,"Label":null,"Description":null,"MinLength":0,"MinValue":null,"MaxValue":null,"IsRequired":true,"IsViewable":false,"IsEditable":false,"IsNillable":false,"IsRestrictedPicklist":false,"PicklistItems":null,"IsSendTime":false,"DisplayOrder":0,"References":null,"RelationshipName":null,"Status":null,"IsContextSpecific":false,"Client":null,"PartnerKey":null,"PartnerProperties":null,"CreatedDate":"0001-01-0
Basically, in splitA[0] should be the first 4000 characters, in split[1] should be in the next 4000 characters and so on until you reach nCharacters
So you basically just want to split a string at a given number of characters?
You can try a regex for that
const splitAtInterval = (string, interval) => {
const r = new RegExp(`.{1,${interval}}`, 'g')
return string.match(r);
}
var text = "Some random string (in your case your JSON string)";
console.log(splitAtInterval(text, 4));
There are other options, just search google for "split string after x characters". for example https://bobbyhadz.com/blog/javascript-split-string-substrings-n-characters
Obviously, as mentioned in the comments, those strings will not be valid json anymore. You will have to fetch all the entries again and connect them via join.

Find specific character from string and change its position to previous character using javascript, jquery

Is it possible to Find specific character from string and change its position to previous character
for example: Let us say there is say a string: Kù Iù Mù
I want output like : ùK ùI ùM
Yes of course! You can go over the string in loop char by char, look at the next position and if it is the char U want, switch the position!
function switchChar(text, charToFind) {
//temp variable for building result
var result = "";
//loop over original string
for (var i = 0; i < text.length; i++) {
//chack not to jump out of array
if (i + 1 < text.length) {
//if next char is the char im looking for
if (text[i + 1] == charToFind) {
//write next char first
result += charToFind;
//then write original char
result += text[i];
//iterate i once more to jump over next char (I appended two chars in this single cycle)
i++;
//if it is not the char Im looking for
} else {
//write it down
result += text[i];
}
//I am at the end
} else {
//write the char
result += text[i];
}
}
return result;
}
console.log(switchChar('Kù Iù Mù', 'ù'))

How to make element in Array change its' place

I'm beginner in JS. I've tried to understand Caesar Cipher ROT13, but it was too complicated for me. So I've tried to write my own code. Here it is below:
function encrip() {
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var str = "Ni Hao";
var string = str.toUpperCase();
for (var i = 0; i < string.length; i++) {
for (var k = 0; k < alphabet.length; k++) {
if(string.charAt(i) == alphabet[k]) {
/* console.log(string.charAt(i) + ' ' + alphabet.indexOf(alphabet[k])); */
}
}
}
}
encrip();
But I am stuck. How to do:
1. Get value from var str and then access to var alphabet , after change each letter from var str value to next 3 from alphabet (var str each element's current position would be changed) For example: Input: Ni Hao ==> output: QL KDR
2. Create universal code, I mean, not only for changing position by 3, but when I give value '5', each element would be changed by next 5 positions from alphabet. So output can be changed when I change its' value
I hope I explained everything clearly. Thanks everyone in advance for help!!
you can use the following function to encrypt english words, the 1st parameter is the string to encrypt and the 2nd for shifting
function encryp(str,pos){
var alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var strUC=str.toUpperCase();
var enc="";
for(var i=0;i<strUC.length;i++){
if(strUC.charAt(i)!=" "){
enc+=alpha.charAt((alpha.indexOf(strUC.charAt(i))+pos)%26)
}
else{
enc+=" "
}
// in your case pos=3
}
return enc;
}
console.log(encryp("NiHao",3));
You don't need two for loops to do this. Iterate over the input string and find the index of each character in the alphabet array, if found add the shift to it to get the encrypted character.
To handle overflow use the modulus operator to cycle through the array.
Also I assume that you are not going use any special symbols to do the encryption.
function encrip(string, shift) {
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
string = string.toUpperCase();
let arr = [];
for (var i = 0; i < string.length; i++) {
let char = alphabet.indexOf(string[i]) !== -1 ? alphabet[(alphabet.indexOf(string[i]) %26) + shift] : " ";
arr.push(char);
}
let encryp = arr.join("");
console.log(encryp);
return encryp;
}
encrip("Ni Hao", 3);
First of all, instead of your inner for loop scanning the whole alphabet array, you can use the built-in function indexOf:
alphabet.indexOf('K') // returns 10
Secondly, you'll want to build up your enciphered string in a separate variable. For each letter, get the index of that letter in the alphabet, add your cipher offset parameter to that index and add the resulting letter from the alphabet to your new string. An important step is that when you add to the index of the letter, you want to make sure the resulting index is within range for the alphabet array. You can do that using the % (modulo) operator, which will wrap high values back round to the start of the array. In full:
function encipher(input, offset) {
var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var str = input.toUpperCase();
var result = '';
for (var i = 0; i < str.length; i++) {
letterIndex = alphabet.indexOf(str.charAt(i));
if (letterIndex === -1) {
result += str[i]; // if the letter isn't found in the alphabet, add it to the result unchanged
continue;
}
cipheredIndex = (letterIndex + offset) % alphabet.length; // wrap index to length of alphabet
result += alphabet[cipheredIndex];
}
console.log(result);
}
encipher('Ni Hao', 5); // output: 'SN MFT'

Printing in Javascript

i have a question that seems basic but i can't seem to figure it out.
Write a program that takes the value of a variable called “input” (declared as any whole number at the top of your program) and outputs a square made of asterisks () as large as the number (input). For example, if the “input” is declared with the value 5, your program would display a square made of 25 asterisks() – ie ; 5 asterisks () high, by 5 asterisks () long.
The code i've come up with so far is below. I don't really understand how to make a string continuously print. If i did star = i then it turns into numbers and will print the numbers. So how do i make it so they connect? I also can't figure out where i should put the new line. console.log(star "\n"); gives me an error. Please help :)
var input = 2;
var star = "*";
var i = 0;
do {
console.log(star);
i++;
} while (i < input);
You can use String.repeat() (ES6 only) along with \r\n to add new line
var input = 5,
star = "*",
str = [],
i = 0;
do {
str.push( Array(input).join(star) ); // use array(length).join
i++;
} while (i < input);
str = str.join("\r\n"); // add breaklines
console.log(str);
console.log Will output a single line to the console containing whatever you pass it as an argument. You are trying to print a line of n asterisks n times.
The first step you should take is constructing the string of asterisks. You can concatenate a string to another with the + operator:
var input = 2;
var star = "*";
var line = "";
for(var i = 0; i < input; i++) {
line = line + star;
}
Once you have constructed line you can then print it n times:
for(var i = 0; i < input; i++) {
console.log(line);
}
Hint: You could create an empty array and then create a loop ending at your wanted number of asterisks after which you will join all the members of the array together. (Writing the code here wouldn't help you much since you mentioned it's an homework).
You could approach this in two ways. If we call your input value n, then we can log either n strings each consisting of n stars, or we can log a single string, containing (n * n) stars, with line breaks after every nth star.
Below is an example of a function that could do this task.
function stars (input) {
var output = ''
for (var i = 0; i < input; i++) {
for (var j = 0; j < input; j++) {
output += '*'
}
output += '\n'
}
return output
}
You can use the repeat-function to print a character multiple times.
var input = 2;
var star = "*";
var i = 0;
while(i++ < input){
console.log(star.repeat(input));
}
This repeats the * character input times in input lines.

JQuery/JavaScript increment number

I am trying to increment a number by a given value each second and retain the formatting using JavaScript or JQuery
I am struggling to do it.
Say I have a number like so:
1412015
the number which this can be incremented by each second is variable it could be anything beween 0.1 and 2.
Is it possible, if the value which it has to be incremented by each second is 0.54 to incremenet the number and have the following output:
1,412,016
1,412,017
1,412,018
Thanks
Eef
I'm not quite sure I understand your incrementation case and what you want to show.
However, I decided to chime in on a solution to format a number.
I've got two versions of a number format routine, one which parses an array, and one which formats with a regular expression. I'll admit they aren't the easiest to read, but I had fun coming up with the approach.
I've tried to describe the lines with comments in case you're curious
Array parsing version:
function formatNum(num) {
//Convert a formatted number to a normal number and split off any
//decimal places if they exist
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//turn the string into a character array and reverse
var arr = parts[0].split('').reverse();
//initialize the return value
var str = '';
//As long as the array still has data to process (arr.length is
//anything but 0)
//Use a for loop so that it keeps count of the characters for me
for( var i = 0; arr.length; i++ ) {
//every 4th character that isn't a minus sign add a comma before
//we add the character
if( i && i%3 == 0 && arr[0] != '-' ) {
str = ',' + str ;
}
//add the character to the result
str = arr.shift() + str ;
}
//return the final result appending the previously split decimal place
//if necessary
return str + ( parts[1] ? '.'+parts[1] : '' );
}
Regular Expression version:
function formatNum(num) {
//Turn a formatted number into a normal number and separate the
//decimal places
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//reverse the string
var str = parts[0].split('').reverse().join('');
//initialize the return value
var retVal = '';
//This gets complicated. As long as the previous result of the regular
//expression replace is NOT the same as the current replacement,
//keep replacing and adding commas.
while( retVal != (str = str.replace(/(\d{3})(\d{1,3})/,'$1,$2')) ) {
retVal = str;
}
//If there were decimal points return them back with the reversed string
if( parts[1] ) {
return retVal.split('').reverse().join('') + '.' + parts[1];
}
//return the reversed string
return retVal.split('').reverse().join('');
}
Assuming you want to output a formatted number every second incremented by 0.54 you could use an interval to do your incrementation and outputting.
Super Short Firefox with Firebug only example:
var num = 1412015;
setInterval(function(){
//Your 0.54 value... why? I don't know... but I'll run with it.
num += 0.54;
console.log( formatNum( num ) );
},1000);
You can see it all in action here: http://jsbin.com/opoze
To increment a value on every second use this structure:
var number = 0; // put your initial value here
function incrementNumber () {
number += 1; // you can increment by anything you like here
}
// this will run incrementNumber() every second (interval is in ms)
setInterval(incrementNumber, 1000);
This will format numbers for you:
function formatNumber(num) {
num = String(num);
if (num.length <= 3) {
return num;
} else {
var last3nums = num.substring(num.length - 3, num.length);
var remindingPart = num.substring(0, num.length - 3);
return formatNumber(remindingPart) + ',' + last3nums;
}
}
function rounded_inc(x, n) {
return x + Math.ceil(n);
}
var x = 1412015;
x = rounded_inc(x, 0.54);

Categories

Resources