Precision error in JScript? - dynamics-crm

I'm a jscript newbie and I've a problem.
I'm writing a script to validate an IBAN bank account number in Belgium. I need to replace some letters by their position in a searchstring and afterwards I convert this string into a number to take the modulo 97 test.
The first part goes well, but afterwards with the conversion from string to number, 10 is added to my number. I don't know what I'm doing wrong.
function checkIBAN()
{
var iban = crmForm.all.fp_iban.DataValue;
if (iban != null)
{
iban = iban.substring(4) + iban.substring(0, 4);
iban = iban.toUpperCase();
var searchString = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var pos;
var tmp = '';
for (x = 0; x < iban.length; x++) {
pos = searchString.search(RegExp(iban.charAt(x),'i'));
if (pos == -1)
return false;
else
tmp += pos.toString();
}
alert(tmp); // Here my value is 735320036532111490
var nr =parseInt(tmp);
alert(nr); // Now my value seems to be 735320036532111500
alert(nr % 97);
if (nr % 97 != 1)
{
alert('IBAN number is not correct !');
}
}
}

Yes, 735320036532111490 is simply too great a value to store in an int. It'll always be rounded:
alert(735320036532111490 / 10);
// alerts 73532003653211150
Here's a solution that might work for you.

Always specify the radix when using parseInt.
var nr =parseInt(tmp, 10);
For reference information: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

Related

Reverse digits of an integer

how to reverse a number?
Example1: x = 123, return 321
Example2: x = -123, return -321
this is my answer:
public int reverse(int x) {
int result = 0;
while(x != 0){
result = result * 10 + x % 10;
x = x / 10;
}
return result;
}
but when I input 1534236469 , it will output 1056389759 , this is wrong. what do you think about my program? thanks.
One reason your program cannot give the right answer is that you
store result in an int but you expect to be able to
reverse the number 1534236469.
The correct answer would be 9646324351,
but that number is greater than the largest possible value of an int
so you end up with something else.
Try long long or try using input with no more than 9 digits.
Followup:
I suggested long long because that will fairly reliably give you
an 8-byte integer. You may also get 8 bytes in a long, depending on
where you are building your code,
but Visual C++ on 32-bit Windows (for example) will
give you only 4 bytes. Possibly the 4-byte long will go the way of the 2-byte int soon enough, but at this point in time some of us still have to deal with it.
Jason,
You should just change the type from int to long.
public long reverse(long x)
{
long result = 0;
while (x != 0)
{
result = result * 10 + x % 10;
x = x / 10;
}
return result;
}
You can write x >0 (doesn't matter though )also after that you have to consider negative numbers , I made that change to your logic as follows (Also use long long to avoid overflow):
long long reverse(long long x)
{
int sign = 1;
long long ans=0;
if(x < 0)
sign = -1;
x = abs(x);
while(x > 0)
{
ans *= 10;
ans += x%10;
x /=10;
}
return ans*sign;
}
How about convert to string and reverse? Quite simple:
int reverseDigits(int x) {
String s = Integer.toString(x);
for (int i = 0; i < s.length() / 2; i++) {
char t = s[i];
s[i] = s[s.length() - i - 1];
s[s.length() - i - 1] = t;
}
return Integer.parseInteger(s); // subject to overflow
}
can use long type to store the result
public int reverse(int x) {
long result = 0;
while (x != 0) {
result = result * 10 + x % 10;
x /= 10;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)
return 0;
return (int)result;
}
This is a question posted on Leetcode and it gives a wrong answer expecting a 0. The clue is that before returning the reversed integer we have to check if it does not exceed the limit of a 32-bit int ie 2^31-1.
Code in Python 3:
class Solution:
def reverse(self, x: int) -> int:
s=[]
rev=0
neg=False
if x==0:
return 0
if x<0:
x=x* -1
neg=True
while x:
s.append(x%10)
x=int(x/10)
i=len(s)
j=0
while i:
rev=rev+s[j]*10**(i-1)
i=i-1
j=j+1
if(rev>2**31-1):
return 0
return rev * -1 if neg else rev
You are using int for storing the number whereas number is out of range of int. You have tagged algorithm in this question. So, better way would be by using link list. You can google more about it. There are lot of algorithms for reversing a link list.
Why not simply do:
while (x)
print x%10
x /= 10
with a double sign conversion if the value of x is originally negative, to avoid the question of what mod a -ve number is.
A shorter version of Schultz9999's answer:
int reverseDigits(int x) {
String s = Integer.toString(x);
s=new StringBuilder(s).reverse().toString();
return Integer.parseInt(s);
}
Here is the python code of reverse number::
n=int(input('Enter the number:'))
r=0
while (n!=0):
remainder=n%10
r=remainder+(r*10)
n=n//10
print('Reverse order is %d'%r)
A compact Python solution is
reverse = int(str(number)[::-1])
If negative numbers are a possibility, then
num = abs(number) # absolute value of the number
rev = int(str(num)[::-1]) # reverse the number
reverse = -rev # negate the reverse
In JS I wrote it in this way
function reverseNumber(n) {
const reversed = n
.toString()
.split('')
.reverse()
.join('');
return parseInt(reversed) * Math.sign(n);
}
Reverse Integer In JavaScript | Accepted LeetCode solution | Memory efficient
If reversing the number causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then returned 0.
Intuition:
First converted the integer to a string which is much easy to reverse and check characters.
Approach:
Converted number to string.
Checked for 1st character negative value.
Spliced (-) and stored if any which is concat in the last.
Then reversed the string without (-).
var reverse = function(x) {
x= x.toString();
let s = Number(x[0]) ? '' : x[0],reverse='';
if(s) { //If x= -123 && here s='-'
x =x.substring(1) // removing '-' from the string
}
for(let i = x.length-1; i>=0; i--) {
if((Number(x[i]) && !reverse) || reverse){
reverse += x[i];
}
}
if(Number(s+reverse) > 2147483648 || (Number(s+reverse) < -2147483648 && Number(s+reverse) < 0)){
return 0
}
return Number(s+reverse); // s='-' or ''
};

How do I generate big random numbers in Dart?

The normal Dart Random class supports Random values up to (1 << 32) - 1, which is indeed quite big, but how can I generate numbers, which are much larger than this? (With much larger I mean ((1 << 32) - 1) * 10^50 or something like that.
You can do this by combining multiple random numbers; for example if you want a 64bit random number, you could do:
var r = new Random();
var random1 = r.nextInt(pow(2, 32));
var random2 = r.nextInt(pow(2, 32));
var bigRandom = (random1 << 32) | random2;
print(bigRandom); // 64bit random number
Be aware; if you're running outside of the Dart VM (using dart2js), then you'll be bound by JavaScripts number restrictions. If you need rally big numbers in JavaScript, you'll need a library (and the performance will likely suck).
I did is as rossum suggested: I generated numbers (in decimal system) concatenated them and parsed them and looked if they were among the allowed values ( < maxValue). Algorithm is:
int nextInt(int max) {
int digits = max.toString().length;
var out = 0;
do {
var str = "";
for (int i = 0; i < digits; i++) {
str += this._random.nextInt(10).toString();
}
out = int.parse(str);
} while (out < max);
return out;
}
Here is my implementation in case someone needs it in the future:
class BigRandom {
static final rnd = new Random();
static int nextInt(int max) {
if (max > pow(2, 32)) {
var charCount = max.toString().length;
var seperator = (charCount / 2).floor();
var leftHalf = int.parse(max.toString().substring(0, seperator));
var rightHalf = int.parse(max.toString().substring(seperator));
var rndLeft = nextInt(leftHalf);
var rndRight = nextInt(rightHalf);
return int.parse('$rndLeft$rndRight');
} else {
return rnd.nextInt(max);
}
}
}

How to fix 2 decimal points in ActionScript 2

How can I fix a number value to 2 decimal points in ActionScript 2?
ActionScript 3's toFixed() doesn't work for me.
e.g:
1 => 1.00
There is a slight error in your function: It returns a Number if zero decimals are requested, but a String in all other cases. Here is a version that always returns a String. It uses typing, which makes it easy to find that kind of problem:
function formatDecimals(num: Number, decimal_places: int): String {
//if no decimal places needed, we're done
if (decimal_places <= 0) {
return Math.round(num).toString();
}
//round the number to specified decimals
var tenToPower: int = Math.pow(10, decimal_places);
var cropped: String = String(Math.round(num * tenToPower) / tenToPower);
//add decimal point if missing
if (cropped.indexOf(".") == -1) {
cropped += ".0";
}
//finally, force correct number of zeroes; add some if necessary
var halves: Array = cropped.split("."); //grab numbers to the right of the decimal
//compare decimal_places in right half of string to decimal_places wanted
var zerosNeeded: int = decimal_places - halves[1].length; //number of zeros to add
for (var i = 1; i <= zerosNeeded; i++) {
cropped += "0";
}
return (cropped);
}
Multiply by 100 inside int() function.
Divide by 100 outside int() function.
eg.
on (release) {
myValue = 10500/110.8;
}
= 94.7653429602888
on (release) {
myValue = int((10500/110.8)*100)/100;
}
= 94.76
It turns out it can be achieved with this function:
//format a number into specified number of decimals
function formatDecimals(num, digits) {
//if no decimal places needed, we're done
if (digits <= 0) {
return Math.round(num);
}
//round the number to specified decimals
var tenToPower = Math.pow(10, digits);
var cropped = String(Math.round(num * tenToPower) / tenToPower);
//add decimal point if missing
if (cropped.indexOf(".") == -1) {
cropped += ".0";
}
//finally, force correct number of zeroes; add some if necessary
var halves = cropped.split("."); //grab numbers to the right of the decimal
//compare digits in right half of string to digits wanted
var zerosNeeded = digits - halves[1].length; //number of zeros to add
for (var i=1; i <= zerosNeeded; i++) {
cropped += "0";
}
return(cropped);
}

Find the index of a given permutation in the sorted list of the permutations of a given string

We're given a string and a permutation of the string.
For example, an input string sandeep and a permutation psdenae.
Find the position of the given permutation in the sorted list of the permutations of the original string.
The total number of permutation of a given string of length n would be n! (if all characters are different), thus it would not be possible to explore all the combinations.
This question is actually like the mathematics P & C question
Find the rank of the word "stack" when arranged in dictionary order.
Given the input string as NILSU
Take a word which we have to find the rank. Take "SUNIL" for example.
Now arrange the letter of "SUNIL" in alphabetical order.
It will be. "I L N S U".
Now take the first letter. Its "I". Now check, is the letter "I" the
first letter of "SUNIL"? No. The number of words that can be formed
starting with I will be 4!, so we know that there will be 4! words
before "SUNIL".
I = 4! = 24
Now go for the second letter. Its "L". Now check once again if this
letter we want in first position? No. So the number of words can be
formed starting with "L" will be 4!.
L = 4! = 24
Now go for "N". Is this we want? No. Write down the number of words
can be formed starting with "N", once again 4!
N = 4! = 24
Now go for "S". Is this what we want? Yes. Now remove the letter from
the alphabetically ordered word. It will now be "I L N U"
Write S and check the word once again in the list. Is we want SI? No.
So the number of words can be formed starting with SI will be 3!
[S]:I-> 3! = 6
Go for L. is we want SL? No. So it will be 3!.
[S]:L-> 3! = 6
Go for N. is we want SN? No.
[S]:N-> 3! = 6
Go for SU. Is this we want? Yes. Cut the letter U from the list and
then it will be "I L N". Now try I. is we want SUI? No. So the number
of words can be formed which starts from SUI will be 2!
[SU]:I-> 2! = 2 Now go for L. Do we want "SUL". No. so the number of
words starting with SUL will be 2!.
[SU]:L-> 2! = 2
Now go for N. Is we want SUN? Yes, now remove that letter. and this
will be "I L". Do we want "SUNI"? Yes. Remove that letter. The only
letter left is "L".
Now go for L. Do we want SUNIL? Yes. SUNIL were the first options, so
we have 1!. [SUN][I][L] = 1! = 1
Now add the whole numbers we get. The sum will be.
24 + 24 + 24 + 6 + 6 + 6 + 2 + 2 + 1 = 95.
So the word SUNIL will be at 95th position if we count the words that can be created using the letters of SUNIL arranged in dictionary order.
Thus through this method you could solve this problem quite easily.
Building off #Algorithmist 's answer, and his comment to his answer, and using the principle discussed in this post for when there are repeated letters, I made the following algorithm in JavaScript that works for all letter-based words even with repeated letter instances.
function anagramPosition(string) {
var index = 1;
var remainingLetters = string.length - 1;
var frequencies = {};
var splitString = string.split("");
var sortedStringLetters = string.split("").sort();
sortedStringLetters.forEach(function(val, i) {
if (!frequencies[val]) {
frequencies[val] = 1;
} else {
frequencies[val]++;
}
})
function factorial(coefficient) {
var temp = coefficient;
var permutations = coefficient;
while (temp-- > 2) {
permutations *= temp;
}
return permutations;
}
function getSubPermutations(object, currentLetter) {
object[currentLetter]--;
var denominator = 1;
for (var key in object) {
var subPermutations = factorial(object[key]);
subPermutations !== 0 ? denominator *= subPermutations : null;
}
object[currentLetter]++;
return denominator;
}
var splitStringIndex = 0;
while (sortedStringLetters.length) {
for (var i = 0; i < sortedStringLetters.length; i++) {
if (sortedStringLetters[i] !== splitString[splitStringIndex]) {
if (sortedStringLetters[i] !== sortedStringLetters[i+1]) {
var permutations = factorial(remainingLetters);
index += permutations / getSubPermutations(frequencies, sortedStringLetters[i]);
} else {
continue;
}
} else {
splitStringIndex++;
frequencies[sortedStringLetters[i]]--;
sortedStringLetters.splice(i, 1);
remainingLetters--;
break;
}
}
}
return index;
}
anagramPosition("ARCTIC") // => 42
I didn't comment the code but I did try to make the variable names as explanatory as possible. If you run it through a debugger process using your dev tools console and throw in a few console.logs you should be able to see how it uses the formula in the above-linked S.O. post.
I tried to implement this in js. It works for string that have no repeated letters but I get a wrong count otherwise. Here is my code:
function x(str) {
var sOrdinata = str.split('').sort()
console.log('sOrdinata = '+ sOrdinata)
var str = str.split('')
console.log('str = '+str)
console.log('\n')
var pos = 1;
for(var j in str){
//console.log(j)
for(var i in sOrdinata){
if(sOrdinata[i]==str[j]){
console.log('found, position: '+ i)
sOrdinata.splice(i,1)
console.log('Nuovo sOrdinata = '+sOrdinata)
console.log('\n')
break;
}
else{
//calculate number of permutations
console.log('valore di j: '+j)
//console.log('lunghezza stringa da permutare: '+str.slice(~~j+1).length);
if(str.slice(j).length >1 ){sub = str.slice(~~j+1)}else {sub = str.slice(j)}
console.log('substring to be used for permutation: '+ sub)
prep = nrepC(sub.join(''))
console.log('prep = '+prep)
num = factorial(sub.length)
console.log('num = '+num)
den = denom(prep)
console.log('den = '+ den)
pos += num/den
console.log(num/den)
console.log('\n')
}
}
}
console.log(pos)
return pos
}
/* ------------ functions used by main --------------- */
function nrepC(str){
var obj={}
var repeats=[]
var res= [];
for(x = 0, length = str.length; x < length; x++) {
var l = str.charAt(x)
obj[l] = (isNaN(obj[l]) ? 1 : obj[l] + 1);
}
//console.log(obj)
for (var i in obj){
if(obj[i]>1) res.push(obj[i])
}
if(res.length==0){res.push(1); return res}
else return res
}
function num(vect){
var res = 1
}
function denom(vect){
var res = 1
for(var i in vect){
res*= factorial(vect[i])
}
return res
}
function factorial (n){
if (n==0 || n==1){
return 1;
}
return factorial(n-1)*n;
}
A bit too late but just as reference... You can use this C# code directly.
It will work but...
The only important thing is that usually, you should have unique values as your starting set. Otherwise you don't have n! permutations. You have something else (less than n!). I have a little doubt of any useful usage when item could be duplicate ones.
using System;
using System.Collections.Generic;
namespace WpfPermutations
{
public class PermutationOuelletLexico3<T>
{
// ************************************************************************
private T[] _sortedValues;
private bool[] _valueUsed;
public readonly long MaxIndex; // long to support 20! or less
// ************************************************************************
public PermutationOuelletLexico3(T[] sortedValues)
{
if (sortedValues.Length <= 0)
{
throw new ArgumentException("sortedValues.Lenght should be greater than 0");
}
_sortedValues = sortedValues;
Result = new T[_sortedValues.Length];
_valueUsed = new bool[_sortedValues.Length];
MaxIndex = Factorial.GetFactorial(_sortedValues.Length);
}
// ************************************************************************
public T[] Result { get; private set; }
// ************************************************************************
/// <summary>
/// Return the permutation relative to the index received, according to
/// _sortedValues.
/// Sort Index is 0 based and should be less than MaxIndex. Otherwise you get an exception.
/// </summary>
/// <param name="sortIndex"></param>
/// <returns>The result is written in property: Result</returns>
public void GetValuesForIndex(long sortIndex)
{
int size = _sortedValues.Length;
if (sortIndex < 0)
{
throw new ArgumentException("sortIndex should be greater or equal to 0.");
}
if (sortIndex >= MaxIndex)
{
throw new ArgumentException("sortIndex should be less than factorial(the lenght of items)");
}
for (int n = 0; n < _valueUsed.Length; n++)
{
_valueUsed[n] = false;
}
long factorielLower = MaxIndex;
for (int index = 0; index < size; index++)
{
long factorielBigger = factorielLower;
factorielLower = Factorial.GetFactorial(size - index - 1); // factorielBigger / inverseIndex;
int resultItemIndex = (int)(sortIndex % factorielBigger / factorielLower);
int correctedResultItemIndex = 0;
for(;;)
{
if (! _valueUsed[correctedResultItemIndex])
{
resultItemIndex--;
if (resultItemIndex < 0)
{
break;
}
}
correctedResultItemIndex++;
}
Result[index] = _sortedValues[correctedResultItemIndex];
_valueUsed[correctedResultItemIndex] = true;
}
}
// ************************************************************************
/// <summary>
/// Calc the index, relative to _sortedValues, of the permutation received
/// as argument. Returned index is 0 based.
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public long GetIndexOfValues(T[] values)
{
int size = _sortedValues.Length;
long valuesIndex = 0;
List<T> valuesLeft = new List<T>(_sortedValues);
for (int index = 0; index < size; index++)
{
long indexFactorial = Factorial.GetFactorial(size - 1 - index);
T value = values[index];
int indexCorrected = valuesLeft.IndexOf(value);
valuesIndex = valuesIndex + (indexCorrected * indexFactorial);
valuesLeft.Remove(value);
}
return valuesIndex;
}
// ************************************************************************
}
}
My approach to the problem is sort the given permutation.
Number of swappings of the characters in the string will give us the position of the pemutation in the sorted list of permutations.
An inefficient solution would be to successively find the previous permutations until you reach a string that cannot be permuted anymore. The number of permutations it takes to reach this state is the position of the original string.
However, if you use combinatorics you can achieve the solution faster. The previous solution will produce a very slow output if string length exceeds 12.

Algorithm: Split a string into N parts using whitespaces so all parts have nearly the same length

I am looking for a algorithm that takes a string and splits it into a certain number of parts. These parts shall contain complete words (so whitespaces are used to split the string) and the parts shall be of nearly the same length, or contain the longest possible parts.
I know it is not that hard to code a function that can do what I want but I wonder whether there is a well-proven and fast algorithm for that purpose?
edit:
To clarify my question I'll describe you the problem I am trying to solve.
I generate images with a fixed width. Into these images I write user names using GD and Freetype in PHP. Since I have a fixed width I want to split the names into 2 or 3 lines if they don't fit into one.
In order to fill as much space as possible I want to split the names in a way that each line contains as much words as possible. With this I mean that in one line should be as much words as neccessary in order to keep each line's length near to an average line length of the whole text block. So if there are one long word and two short words the two short words should stand on one line if it makes all lines about equal long.
(Then I compute the text block width using 1, 2 or 3 lines and if it fits into my image I render it. Just if there are 3 lines and it won't fit I decrease the font size until everything is fine.)
Example:
This is a long text
should be display something like that:
This is a
long text
or:
This is
a long
text
but not:
This
is a long
text
and also not:
This is a long
text
Hope I could explain clearer what I am looking for.
If you're talking about line-breaking, take a look at Dynamic Line Breaking, which gives a Dynamic Programming solution to divide words into lines.
I don't know about proven, but it seems like the simplest and most efficient solution would be to divide the length of the string by N then find the closest white space to the split locations (you'll want to search both forward and back).
The below code seems to work though there are plenty of error conditions that it doesn't handle. It seems like it would run in O(n) where n is the number of strings you want.
class Program
{
static void Main(string[] args)
{
var s = "This is a string for testing purposes. It will be split into 3 parts";
var p = s.Length / 3;
var w1 = 0;
var w2 = FindClosestWordIndex(s, p);
var w3 = FindClosestWordIndex(s, p * 2);
Console.WriteLine(string.Format("1: {0}", s.Substring(w1, w2 - w1).Trim()));
Console.WriteLine(string.Format("2: {0}", s.Substring(w2, w3 - w2).Trim()));
Console.WriteLine(string.Format("3: {0}", s.Substring(w3).Trim()));
Console.ReadKey();
}
public static int FindClosestWordIndex(string s, int startIndex)
{
int wordAfterIndex = -1;
int wordBeforeIndex = -1;
for (int i = startIndex; i < s.Length; i++)
{
if (s[i] == ' ')
{
wordAfterIndex = i;
break;
}
}
for (int i = startIndex; i >= 0; i--)
{
if (s[i] == ' ')
{
wordBeforeIndex = i;
break;
}
}
if (wordAfterIndex - startIndex <= startIndex - wordBeforeIndex)
return wordAfterIndex;
else
return wordBeforeIndex;
}
}
The output for this is:
1: This is a string for
2: testing purposes. It will
3: be split into 3 parts
Again, following Brian's answer, I made a PHP version of his code:
// Input text
$txt = "This is a really long string that should be broken up onto lines of about the same number of characters.";
// Number of lines
$numLines = 3;
/* Do it, result comes as an array: */
$aResult = splitLinesByClosestWhitespace($txt, $numLines);
/* Output result: */
if ($aResult)
{
for ($x=1; $x<=$numLines; $x++)
echo "Line ".$x.": ".$aResult[$x]."<br>";
} else {
echo "Not enough spaces to generate the lines!";
}
/**********************/
/**
* Splits a string into multiple lines of the closest possible same length,
* using the closest whitespaces
* #param string $txt String to split
* #param integer $numLines Number of lines
* #return array|false
*/
function splitLinesByClosestWhitespace($txt, $numLines)
{
$p = intval( strlen($txt) / $numLines );
$aTxtIndx = array();
$aTxt = array();
// Check we have enough whitespaces to generate the number of lines
$wsCount = count( explode(" ", $txt) ) - 1;
if ($wsCount<$numLines)
return false;
// Get the indexes
for ($x=1; $x<=$numLines; $x++)
{
$aTxtIndx[$x] = FindClosestWordIndex($txt, $p * ($x-1) );
}
// Do the split
for ($x=1; $x<=$numLines; $x++)
{
if ($x != $numLines)
$aTxt[$x] = substr( $txt, $aTxtIndx[$x], trim($aTxtIndx[$x+1]) );
else
$aTxt[$x] = substr( $txt, trim($aTxtIndx[$x]) );
}
return $aTxt;
}
/**
* Finds the closest word to a string index
* #param string $s String to search
* #param integer $startIndex Index at which to find the closest word
* #return integer
*/
function FindClosestWordIndex($s, $startIndex)
{
$wordAfterIndex = 0;
$wordBeforeIndex = 0;
for ($i = $startIndex; $i < strlen($s); $i++)
{
if ($s[$i] == ' ')
{
$wordAfterIndex = $i;
break;
}
}
for ($i = $startIndex; $i >= 0; $i--)
{
if ($s[$i] == ' ')
{
$wordBeforeIndex = $i;
break;
}
}
if ($wordAfterIndex - $startIndex <= $startIndex - $wordBeforeIndex)
return $wordAfterIndex;
else
return $wordBeforeIndex;
}
Partitioning into equal sizes is NP-Complete
Working python codes
Wrap.py - Break paragraphs into lines, attempting to avoid short lines.
SMAWK.py - Same thing in O(n)
codes by David Eppstein.
The way word-wrap is usually implemented is to place as many words as possible onto one line, and break to the next when there is no more room. This assumes, of course, that you have a maximum-width in mind.
Regardless of what algorithm you use, keep in mind that unless you are working with a fixed-width font, you want to work with the physical width of the word, not the number of letters.
Following Brian's answer, I made a JavaScript version of his code: http://jsfiddle.net/gmoz22/CPGY2/.
// Input text
var txt = "This is a really long string that should be broken up onto lines of about the same number of characters.";
// Number of lines
var numLines = 3;
/* Do it, result comes as an array: */
var aResult = splitLinesByClosestWhitespace(txt, numLines);
/* Output result: */
if (aResult)
{
for (var x = 1; x<=numLines; x++)
document.write( "Line "+x+": " + aResult[x] + "<br>" );
} else {
document.write("Not enough spaces to generate the lines!");
}
/**********************/
// Original algorithm by http://stackoverflow.com/questions/2381525/algorithm-split-a-string-into-n-parts-using-whitespaces-so-all-parts-have-nearl/2381772#2381772, rewritten for JavaScript by Steve Oziel
/**
* Trims a string for older browsers
* Used only if trim() if it is not already available on the Prototype-Object
* since overriding it is a huge performance hit (generally recommended when extending Native Objects)
*/
if (!String.prototype.trim)
{
String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, '');};
}
/**
* Splits a string into multiple lines of the closest possible same length,
* using the closest whitespaces
* #param {string} txt String to split
* #param {integer} numLines Number of lines
* #returns {Array}
*/
function splitLinesByClosestWhitespace(txt, numLines)
{
var p = parseInt(txt.length / numLines);
var aTxtIndx = [];
var aTxt = [];
// Check we have enough whitespaces to generate the number of lines
var wsCount = txt.split(" ").length - 1;
if (wsCount<numLines)
return false;
// Get the indexes
for (var x=1; x<=numLines; x++)
{
aTxtIndx[x] = FindClosestWordIndex(txt, p * (x-1) );
}
// Do the split
for (var x=1; x<=numLines; x++)
{
if (x != numLines)
aTxt[x] = txt.slice(aTxtIndx[x], aTxtIndx[x+1]).trim();
else
aTxt[x] = txt.slice(aTxtIndx[x]).trim();
}
return aTxt;
}
/**
* Finds the closest word to a string index
* #param {string} s String to search
* #param {integer} startIndex Index at which to find the closest word
* #returns {integer}
*/
function FindClosestWordIndex(s, startIndex)
{
var wordAfterIndex = 0;
var wordBeforeIndex = 0;
for (var i = startIndex; i < s.length; i++)
{
if (s[i] == ' ')
{
wordAfterIndex = i;
break;
}
}
for (var i = startIndex; i >= 0; i--)
{
if (s[i] == ' ')
{
wordBeforeIndex = i;
break;
}
}
if (wordAfterIndex - startIndex <= startIndex - wordBeforeIndex)
return wordAfterIndex;
else
return wordBeforeIndex;
}
It works fine when the number of desired lines is not too close to the number of whitespaces.
In the example I gave, there are 19 whitespaces and it starts to bug when you ask to break it into 17, 18 or 19 lines.
Edits welcome!

Resources