Javascript print array of numbers out in tabular format - javascript

Hi I have an array of numbers and a K number which is the number of numbers on each line. I want to display numbers like this:
+---+---+
|123| 5|
+---+---+
| 6| 14|
+---+---+
so array = [123, 5, 6, 14] and K = 2, and there are pluses and minuses and pipes. The number of minuses is equal to number of digits in biggest number.
How can I write this in Javascript?
I have:
let res = ""
let max = Math.max(null, A)
let digits = max.toString().length;
function line(numPlus, numMinus) {
let string = "";
for (let i = 0; i < numPlus; i++) {
string += "+"
for(let j = 0; j < numMinus; j++) {
string += "-"
}
string += "+"
}
}
line(K+1, digits);

let array = [123, 5, 6, 14];
let k = 2;
let m = Math.max(...(array.map(e => e.toString().length)));
let t = new Array(k+1).fill("+").join("-".repeat(m));
let pa = array.map(e => e.toString().padStart(m, " "));
let str = "";
for (let i = 0; i < array.length/k; i++) {
let s = pa.slice(k*i, k*i+k);
while (s.length < k) s.push(" ".repeat(m));
str += t + "\n|" + s.join("|") + "|\n";
}
console.log(str + t);

Something Like This Maybe
let numbers = [100,25555,60,21,456,789,231,54,2,4,13,6,579,4562156, -5, 0.5, -1.5]
let maxLength = 0;
for(let i = 0; i < numbers.length; i++){
if(maxLength < numbers[i].toString().length){
maxLength = numbers[i].toString().length
}
}
function printDivider(cells){
let row = '+';
for(let i = 0; i < cells; i++){
for(let j = 0; j < maxLength; j++){
row+= '-'
}
row += '+';
}
console.log(row)
}
function printNumberRow(cells){
let row = '|'
for(let i = 0; i< cells; i++){
if(numbers.length !== 0){
let currentNumber = numbers.shift().toString();
currentNumber = currentNumber.padStart(maxLength, ' ');
row+=currentNumber;
}
else{
row+= ''.padStart(maxLength, ' ');
}
row += '|';
}
console.log(row);
}
function printGraph(numbersPerRow){
let maxRows = Math.round(numbers.length / numbersPerRow)
if(numbers.length % numbersPerRow >= 1){
maxRows++;
}
for(let i = 0; i < maxRows; i++){
printDivider(numbersPerRow)
printNumberRow(numbersPerRow)
printDivider(numbersPerRow)
}
}
printGraph(5)
+-------+-------+-------+-------+-------+
| 100| 25555| 60| 21| 456|
+-------+-------+-------+-------+-------+
+-------+-------+-------+-------+-------+
| 789| 231| 54| 2| 4|
+-------+-------+-------+-------+-------+
+-------+-------+-------+-------+-------+
| 13| 6| 579|4562156| -5|
+-------+-------+-------+-------+-------+
+-------+-------+-------+-------+-------+
| 0.5| -1.5| | | |
+-------+-------+-------+-------+-------+

//A simple and effective solution for exact result
import java.util.*;
class Solution {
public void solution(int[] A, int K) {
int maxLength = 0;
ArrayList<Integer> arr = new ArrayList<>();
for(int x :A){
arr.add(x);
}
for(int i = 0; i < A.length; i++){
if(maxLength < Integer.toString(A[i]).length()){
maxLength = Integer.toString(A[i]).length();
}
}
int completeRow = A.length / K;
int iRow = A.length % K;
if(completeRow>0){
printDivider(K, maxLength,arr);
}
else{
printDivider(iRow,maxLength,arr);
}
System.out.println();
for(int i=0;i<completeRow;i++){
printNumberRow(K, maxLength,arr);
System.out.println();
printDivider(K, maxLength,arr);
System.out.println();
}
if(iRow > 0){
printNumberRow(iRow, maxLength,arr);
System.out.println();
printDivider(iRow, maxLength,arr);
System.out.println();
}
}
void printDivider(int cells, int maxLength ,ArrayList<Integer> A){
String row = "+";
for(int i = 0; i < cells; i++){
for(int j = 0; j < maxLength; j++){
row+="-";
}
row += "+";
}
System.out.print(row);
}
public void printNumberRow(int cells,int maxLength, ArrayList A){
String row = "|";
for(int i = 0; i< cells; i++){
if(A.size() != 0){
int num=A.get(0);
A.remove(0);
// String currentNumber = Integer.toString(num);
String aa = "" ;
int intlength = Integer.toString(num).length() ;
for(int j = 0 ; j < maxLength-intlength ; j++ ) {
aa = aa+" " ;
}
aa =aa + Integer.toString(num) ;
row+=aa;
}
// else{
// row+= ''.padStart(maxLength, ' ');
// }
row += '|';
}
System.out.print(row);
}
}

Here is the Java solution. I am just formatting #user17315860 answer.
His answer is correct but not at all ridable.
import java.util.ArrayList;
class Solution {
static void solution(int[] A, int K) {
int maxLength = 0;
ArrayList<Integer> arr = new ArrayList<>();
for (int x : A) {
arr.add(x);
}
for (int i = 0; i < A.length; i++) {
if (maxLength < Integer.toString(A[i]).length()) {
maxLength = Integer.toString(A[i]).length();
}
}
int completeRow = A.length / K;
int iRow = A.length % K;
if (completeRow > 0) {
printDivider(K, maxLength, arr);
} else {
printDivider(iRow, maxLength, arr);
}
System.out.println();
for (int i = 0; i < completeRow; i++) {
printNumberRow(K, maxLength, arr);
System.out.println();
printDivider(K, maxLength, arr);
System.out.println();
}
if (iRow > 0) {
printNumberRow(iRow, maxLength, arr);
System.out.println();
printDivider(iRow, maxLength, arr);
System.out.println();
}
}
static void printDivider(int cells, int maxLength, ArrayList<Integer> A) {
String row = "+";
for (int i = 0; i < cells; i++) {
for (int j = 0; j < maxLength; j++) {
row += "-";
}
row += "+";
}
System.out.print(row);
}
static public void printNumberRow(int cells, int maxLength, ArrayList<Integer> A) {
String row = "|";
for (int i = 0; i < cells; i++) {
if (A.size() != 0) {
int num = A.get(0);
A.remove(0);
// String currentNumber = Integer.toString(num);
String aa = "";
int intlength = Integer.toString(num).length();
for (int j = 0; j < maxLength - intlength; j++) {
aa = aa + " ";
}
aa = aa + Integer.toString(num);
row += aa;
}
// else{
// row+= ''.padStart(maxLength, ' ');
// }
row += '|';
}
System.out.print(row);
}
public static void main(String[] args) {
int[] A = new int[] { 4, 35, 80, 123, 12345, 44, 8, 5, 24, 3,22,35 };
solution(A, 4);
}
}

Related

longest common substring Multiple Input in JS

function LCSubStr(X, Y) {
let m = X.length;
let n = Y.length;
let result = 0;
let end;
let len = new Array(4);
for (let i = 0; i < len.length; i++) {
len[i] = new Array(n);
for (let j = 0; j < n; j++) {
len[i][j] = 0;
}
}
let currRow = 0;
for (let i = 0; i <= m; i++) {
for (let j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
len[currRow][j] = 0;
}
else if (X[i - 1] == Y[j - 1]) {
len[currRow][j] = len[1 - currRow][j - 1] + 1;
if (len[currRow][j] > result) {
result = len[currRow][j];
end = i - 1;
}
}
else {
len[currRow][j] = 0;
}
}
currRow = 1 - currRow;
}
if (result == 0) {
return "-1";
}
return X.substr(end - result + 1, result);
}
// Driver Code
let X = "GeeksforGeeks";
let Y = "GeeksQuiz";
// function call
document.write(LCSubStr(X, Y));
How can I convert this code for multiple input?
I checked many lcs code but no one works with
ABCQEFDEFGHIJ BCXEFGYZBCDEWEFGHU > EFGH
This one just works good without any problem. I should convert this one for multiple input in Javascript.
Now we have X,Y but it shoulde be with multiple inputs.

JavaScript pyramid

I'm trying to print a pyramid that has odd numbers for edges. For example output should be:
.......5
...3,4,3
1,2,3,2,1
(dots are here just to show formating)
I managed to write:
function p(n){
let string = "";
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n - i; j++) {
string += " " ;
}
for (let k = 1; k <= 2*i-1; k++) {
string += n-k +1;
}
string += "\n";
}
console.log(string);
}
p(5);
But I'm not sure how to continue to get wanted result
You can try it :
function p(n){
let string = ""
for (let i = 0; i <= n/2; i++) {
let k = n - 2 * i
for (let j =0; j < Math.floor(n/2)*2 + 1; j++) {
if(j < Math.floor(n/2) - i) {
string += " ";
}
if( j >= Math.floor(n/2) - i && j <= Math.floor(n/2) + i) {
string += k;
j < Math.floor(n/2) ? k++ : k--
}
if(j > Math.floor(n/2) + i ) {
string += " ";
}
}
string += "\n";
}
console.log(string);
}
p(7);

How to compile this C code to WebAssembly correctly?

I have the C code:
int edges_start[3000];
int edges_end[3000];
float edges_len[3000];
int g_links_id[1000][100];
float g_links_weight[1000][100];
int cache_id[1000];
float cache_distance[1000];
int cache_prev[1000];
int cache_links_id[1000][100];
float cache_links_weight[1000][100];
int queue_id[1000];
float queue_distance[1000];
int queue_prev[1000];
int queue_links_id[1000][100];
float queue_links_weight[1000][100];
void* memcpy(char* dst, char* src, int count) {
while(count--) *dst++ = *src++;
}
void init_cpp() {
for (int i=0; i < 1000; i++) {
cache_id[i] = -2;
queue_id[i] = -2;
cache_distance[i] = 100000;
queue_distance[i] = 100000;
cache_prev[i] = -2;
queue_prev[i] = -2;
for (int j=0; j < 100; j++) {
queue_links_id[i][j] = -2;
queue_links_weight[i][j] = 100000;
cache_links_id[i][j] = -2;
cache_links_weight[i][j] = 100000;
}
}
}
void init_edges_cpp() {
for (int i=0; i < 3000; i++) {
edges_start[i] = -2;
edges_end[i] = -2;
edges_len[i] = -2.0;
}
for (int i=0; i < 1000; i++) {
for (int j=0; j < 100; j++) {
g_links_id[i][j] = -2;
g_links_weight[i][j] = -2.0;
}
}
}
void add_edge_cpp(int index, int start, int end, float len) {
edges_start[index] = start;
edges_end[index] = end;
edges_len[index] = len;
}
void fill_graph_cpp() {
for (int i=0; i < 3000; i++) {
int s = edges_start[i];
int e = edges_end[i];
float len = edges_len[i];
if (s == -2) {
break;
}
int links_len = 0;
for (int j=0; j < 100; j++) {
if (g_links_id[s][j] == -2) {
links_len = j;
break;
}
}
g_links_id[s][links_len] = e;
g_links_weight[s][links_len] = len;
for (int j=0; j < 100; j++) {
if (g_links_id[e][j] == -2) {
links_len = j;
break;
}
}
g_links_id[e][links_len] = s;
g_links_weight[e][links_len] = len;
}
}
void get_dists_cpp(int a, int L) {
int i = L;
while (--i >= 0) {
for (int j = 0; j < 100; j++) {
//console.log()
if (g_links_id[i][j] == -2) {
break;
}
cache_links_id[i][j] = g_links_id[i][j];
cache_links_weight[i][j] = g_links_weight[i][j];
}
cache_id[i] = i;
}
queue_id[0] = cache_id[a];
cache_distance[a] = 0;
queue_distance[0] = cache_distance[a];
queue_prev[0] = queue_prev[a];
for (int j=0; j < 100; j++) {
queue_links_id[0][j] = cache_links_id[a][j];
queue_links_weight[0][j] = cache_links_weight[a][j];
}
i=0;
int queue_len = 1;
while (i < queue_len) {
int node_id = queue_id[i];
float node_distance = queue_distance[i];
int node_prev = queue_prev[i];
int j=0;
for (int k=0; k < 100; k++) {
if (queue_links_id[i][k] == -2) {
j=k;
break;
}
}
while (--j >= 0) {
int link_id = queue_links_id[i][j];
float link_weight = queue_links_weight[i][j];
int c_id = cache_id[link_id];
float c_distance = cache_distance[link_id];
int c_prev = cache_prev[link_id];
float d = node_distance + link_weight;
if (d < c_distance) {
cache_prev[link_id] = node_id;
cache_distance[link_id] = d;
int last_ind = queue_len;
queue_id[last_ind] = cache_id[link_id];
queue_distance[last_ind] = cache_distance[link_id];
for (int k=0; k < 100; k++) {
if (cache_links_id[link_id][k] == -2) {
break;
}
queue_links_id[last_ind][k] = cache_links_id[link_id][k];
queue_links_weight[last_ind][k] = cache_links_weight[link_id][k];
}
queue_prev[last_ind] = cache_prev[link_id];
queue_len++;
}
}
i++;
}
}
int get_edges_start(int index) {
return edges_start[index];
}
float get_cache_distance(int index) {
return cache_distance[index];
}
int get_cache_prev(int index) {
return cache_prev[index];
}
int main() {
init_edges_cpp();
init_cpp();
add_edge_cpp(0, 0, 2, 1);
add_edge_cpp(1, 0, 1, 1);
add_edge_cpp(2, 1, 2, 1);
add_edge_cpp(3, 2, 3, 1);
add_edge_cpp(4, 2, 4, 1);
add_edge_cpp(5, 3, 4, 1);
fill_graph_cpp();
get_dists_cpp(0, 5);
/*
for (int i=0; i < 10; i++) {
cout << i << " " << get_cache_distance(i) << " " << get_cache_prev(i) << endl;
}
*/
return 0;
}
It works correct, you can check it here
But, when I tried to compile it to wasm with this website
I put in the left field this code: https://pastebin.com/NG10Z0jX
And in the right field that js code:
var wasmModule = new WebAssembly.Module(wasmCode);
var wasmInstance = new WebAssembly.Instance(wasmModule, wasmImports);
var wasm_module = wasmInstance.exports
wasm_module.main();
for (var i=0; i < 5; i++) {
var c1 = wasm_module.get_cache_distance(i);
var c2 = wasm_module.get_cache_prev(i);
log(i+" " +c1 + " " + c2)
}
It returned wrong output:
vert: 0 dist: 0 prev -2
vert: 1 dist: 100000 prev -2
vert: 2 dist: 100000 prev -2
vert: 3 dist: 100000 prev -2
vert: 4 dist: 100000 prev -2
It should return this:
vert: 0 dist: 0.000000 prev: -2
vert: 1 dist: 1.000000 prev: 0
vert: 2 dist: 1.000000 prev: 0
vert: 3 dist: 2.000000 prev: 2
vert: 4 dist: 2.000000 prev: 2
How to compile this C code to WebAssembly correctly?
The answer is to put this in C code:
void* memcpy(char* dst, char* src, int count) {
void* p=dst;
while(count--) *dst++ = *src++;
return p;
}

Different Implementation of the same JS program in C++

I recently raised a question about implementing sieve of eratosthenes in Javascript on SO and here's the working answer I got:
function sieve(low, high) {
var primeArray = [], ll = Math.sqrt(high), output = [];
for (var i = 2; i <= high; i++) {
primeArray[i] = true;
}
for (var i = 2; i <= ll; i++) {
if (primeArray[i]) {
for (var j = i * i; j <= high; j += i) {
primeArray[j] = false;
}
}
}
for (var i = 2; i <= ll; i++) {
if(primeArray[i]) {
var segmentStart = Math.ceil(low/i) * i;
// need this test to ensure we are not deleting primes
if (primeArray[segmentStart]) segmentStart += i;
for(var j = segmentStart; j <= high; j+=i) {
primeArray[j] = false;
}
}
}
for(var i = low; i <= high; i++) {
if(primeArray[i]) {
output.push(i);
}
}
return output;
}
console.log(sieve(1, 20));
I tried implementing the same in C++
However the end result is quite different.
My C++ program is somehow ignoring the first 2 prime numbers while maintaining 1 as a prime.
Here's the same program in C++
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int low, high;
cout << "Enter lower bound: ";
cin >> low;
cout << "Enter upper bound: ";
cin >> high;
int root = floor(sqrt(high));
int primes[high];
for(int i = 2; i <= high; i++)
{
primes[i] = true;
}
for (int i = 2; i <= root; i++) {
if (primes[i]) {
for (int j = i * i; j <= high; j += i) {
primes[j] = false;
}
}
}
for (int i = 2; i <= root; i++) {
if(primes[i]) {
int segmentStart = ceil(low/i) * i;
if (primes[segmentStart]) segmentStart += i;
for(int j = segmentStart; j <= high; j+=i) {
primes[j] = false;
}
}
}
for(int i = low; i <= high; i++) {
if(primes[i]) {
cout << i;
}
}
return 0;
}
Found the solution.
low/i division operation in int segmentStart = ceil(low/i) * i; was returning an integer and hence it was ignoring results < 1;
I typecasted i as a double to solve this problem like this:
int segmentStart = ceil(low/(double)i) * i;

Longest palindrome in a string

I wrote the following function to find the longest palindrome in a string. It works fine but it won't work for words like "noon" or "redder". I fiddled around and changed the first line in the for loop from:
var oddPal = centeredPalindrome(i, i);
to
var oddPal = centeredPalindrome(i-1, i);
and now it works, but I'm not clear on why. My intuition is that if you are checking an odd-length palindrome it will have one extra character in the beginning (I whiteboarded it out and that's the conclusion I came to). Am I on the right track with my reasoning?
var longestPalindrome = function(string) {
var length = string.length;
var result = "";
var centeredPalindrome = function(left, right) {
while (left >= 0 && right < length && string[left] === string[right]) {
//expand in each direction.
left--;
right++;
}
return string.slice(left + 1, right);
};
for (var i = 0; i < length - 1; i++) {
var oddPal = centeredPalindrome(i, i);
var evenPal = centeredPalindrome(i, i);
if (oddPal.length > result.length)
result = oddPal;
if (evenPal.length > result.length)
result = evenPal;
}
return "the palindrome is: " + result + " and its length is: " + result.length;
};
UPDATE:
After Paul's awesome answer, I think it makes sense to change both variables for clarity:
var oddPal = centeredPalindrome(i-1, i + 1);
var evenPal = centeredPalindrome(i, i+1);
You have it backwards - if you output the "odd" palindromes (with your fix) you'll find they're actually even-length.
Imagine "noon", starting at the first "o" (left and right). That matches, then you move them both - now you're comparing the first "n" to the second "o". No good. But with the fix, you start out comparing both "o"s, and then move to both "n"s.
Example (with the var oddPal = centeredPalindrome(i-1, i); fix):
var longestPalindrome = function(string) {
var length = string.length;
var result = "";
var centeredPalindrome = function(left, right) {
while (left >= 0 && right < length && string[left] === string[right]) {
//expand in each direction.
left--;
right++;
}
return string.slice(left + 1, right);
};
for (var i = 0; i < length - 1; i++) {
var oddPal = centeredPalindrome(i, i + 1);
var evenPal = centeredPalindrome(i, i);
if (oddPal.length > 1)
console.log("oddPal: " + oddPal);
if (evenPal.length > 1)
console.log("evenPal: " + evenPal);
if (oddPal.length > result.length)
result = oddPal;
if (evenPal.length > result.length)
result = evenPal;
}
return "the palindrome is: " + result + " and its length is: " + result.length;
};
console.log(
longestPalindrome("nan noon is redder")
);
This will be optimal if the largest palindrome is found earlier.
Once its found it will exit both loops.
function isPalindrome(s) {
//var rev = s.replace(/\s/g,"").split('').reverse().join(''); //to remove space
var rev = s.split('').reverse().join('');
return s == rev;
}
function longestPalind(s) {
var maxp_length = 0,
maxp = '';
for (var i = 0; i < s.length; i++) {
var subs = s.substr(i, s.length);
if (subs.length <= maxp_length) break; //Stop Loop for smaller strings
for (var j = subs.length; j >= 0; j--) {
var sub_subs = subs.substr(0, j);
if (sub_subs.length <= maxp_length) break; // Stop loop for smaller strings
if (isPalindrome(sub_subs)) {
maxp_length = sub_subs.length;
maxp = sub_subs;
}
}
}
return maxp;
}
Here is another take on the subject.
Checks to make sure the string provided is not a palindrome. If it is then we are done. ( Best Case )
Worst case 0(n^2)
link to
gist
Use of dynamic programming. Break each problem out into its own method, then take the solutions of each problem and add them together to get the answer.
class Palindrome {
constructor(chars){
this.palindrome = chars;
this.table = new Object();
this.longestPalindrome = null;
this.longestPalindromeLength = 0;
if(!this.isTheStringAPalindrome()){
this.initialSetupOfTableStructure();
}
}
isTheStringAPalindrome(){
const reverse = [...this.palindrome].reverse().join('');
if(this.palindrome === reverse){
this.longestPalindrome = this.palindrome;
this.longestPalindromeLength = this.palindrome.length;
console.log('pal is longest', );
return true;
}
}
initialSetupOfTableStructure(){
for(let i = 0; i < this.palindrome.length; i++){
for(let k = 0; k < this.palindrome.length; k++){
this.table[`${i},${k}`] = false;
}
}
this.setIndividualsAsPalindromes();
}
setIndividualsAsPalindromes(){
for(let i = 0; i < this.palindrome.length; i++){
this.table[`${i},${i}`] = true;
}
this.setDoubleLettersPlaindrome();
}
setDoubleLettersPlaindrome(){
for(let i = 0; i < this.palindrome.length; i++){
const firstSubstring = this.palindrome.substring(i, i + 1);
const secondSubstring = this.palindrome.substring(i+1, i + 2);
if(firstSubstring === secondSubstring){
this.table[`${i},${i + 1}`] = true;
if(this.longestPalindromeLength < 2){
this.longestPalindrome = firstSubstring + secondSubstring;
this.longestPalindromeLength = 2;
}
}
}
this.setAnyPalindromLengthGreaterThan2();
}
setAnyPalindromLengthGreaterThan2(){
for(let k = 3; k <= this.palindrome.length; k++){
for(let i = 0; i <= this.palindrome.length - k; i++){
const j = i + k - 1;
const tableAtIJ = this.table[`${i+1},${j-1}`];
const stringToCompare = this.palindrome.substring(i, j +1);
const firstLetterInstringToCompare = stringToCompare[0];
const lastLetterInstringToCompare = [...stringToCompare].reverse()[0];
if(tableAtIJ && firstLetterInstringToCompare === lastLetterInstringToCompare){
this.table[`${i},${j}`] = true;
if(this.longestPalindromeLength < stringToCompare.length){
this.longestPalindrome = stringToCompare;
this.longestPalindromeLength = stringToCompare.length;
}
}
}
}
}
printLongestPalindrome(){
console.log('Logest Palindrome', this.longestPalindrome);
console.log('from /n', this.palindrome );
}
toString(){
console.log('palindrome', this.palindrome);
console.log(this.table)
}
}
// const palindrome = new Palindrome('lollolkidding');
// const palindrome = new Palindrome('acbaabca');
const palindrome = new Palindrome('acbaabad');
palindrome.printLongestPalindrome();
//palindrome.toString();
function longestPalindrome(str){
var arr = str.split("");
var endArr = [];
for(var i = 0; i < arr.length; i++){
var temp = "";
temp = arr[i];
for(var j = i + 1; j < arr.length; j++){
temp += arr[j];
if(temp.length > 2 && temp === temp.split("").reverse().join("")){
endArr.push(temp);
}
}
}
var count = 0;
var longestPalindrome = "";
for(var i = 0; i < endArr.length; i++){
if(count >= endArr[i].length){
longestPalindrome = endArr[i-1];
}
else{
count = endArr[i].length;
}
}
console.log(endArr);
console.log(longestPalindrome);
return longestPalindrome;
}
longestPalindrome("abracadabra"));
let str = "HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE";
let rev = str.split("").reverse().join("").trim();
let len = str.length;
let a="";
let result = [];
for(let i = 0 ; i < len ; i++){
for(let j = len ; j > i ; j--){
a = rev.slice(i,j);
if(str.includes(a)){
result.push(a);
break;
}
}
}
result.sort((a,b) => { return b.length - a.length})
let logPol = result.find((value)=>{
return value === value.split('').reverse().join('') && value.length > 1
})
console.log(logPol);
function longest_palindrome(s) {
if (s === "") {
return "";
}
let arr = [];
let _s = s.split("");
for (let i = 0; i < _s.length; i++) {
for (let j = 0; j < _s.length; j++) {
let word = _s.slice(0, j + 1).join("");
let rev_word = _s
.slice(0, j + 1)
.reverse()
.join("");
if (word === rev_word) {
arr.push(word);
}
}
_s.splice(0, 1);
}
let _arr = arr.sort((a, b) => a.length - b.length);
for (let i = 0; i < _arr.length; i++) {
if (_arr[arr.length - 1].length === _arr[i].length) {
return _arr[i];
}
}
}
longest_palindrome('bbaaacc')
//This code will give you the first longest palindrome substring into the string
var longestPalindrome = function(string) {
var length = string.length;
var result = "";
var centeredPalindrome = function(left, right) {
while (left >= 0 && right < length && string[left] === string[right]) {
//expand in each direction.
left--;
right++;
}
return string.slice(left + 1, right);
};
for (var i = 0; i < length - 1; i++) {
var oddPal = centeredPalindrome(i, i + 1);
var evenPal = centeredPalindrome(i, i);
if (oddPal.length > 1)
console.log("oddPal: " + oddPal);
if (evenPal.length > 1)
console.log("evenPal: " + evenPal);
if (oddPal.length > result.length)
result = oddPal;
if (evenPal.length > result.length)
result = evenPal;
}
return "the palindrome is: " + result + " and its length is: " + result.length;
};
console.log(longestPalindrome("n"));
This will give wrong output so this condition need to be taken care where there is only one character.
public string LongestPalindrome(string s) {
return LongestPalindromeSol(s, 0, s.Length-1);
}
public static string LongestPalindromeSol(string s1, int start, int end)
{
if (start > end)
{
return string.Empty;
}
if (start == end)
{
char ch = s1[start];
string s = string.Empty;
var res = s.Insert(0, ch.ToString());
return res;
}
if (s1[start] == s1[end])
{
char ch = s1[start];
var res = LongestPalindromeSol(s1, start + 1, end - 1);
res = res.Insert(0, ch.ToString());
res = res.Insert(res.Length, ch.ToString());
return res;
}
else
{
var str1 = LongestPalindromeSol(s1, start, end - 1);
var str2 = LongestPalindromeSol(s1, start, end - 1);
if (str1.Length > str2.Length)
{
return str1;
}
else
{
return str2;
}
}
}
This is in JS ES6. much simpler and works for almost all words .. Ive tried radar, redder, noon etc.
const findPalindrome = (input) => {
let temp = input.split('')
let rev = temp.reverse().join('')
if(input == rev){
console.log('Palindrome', input.length)
}
}
//i/p : redder
// "Palindrome" 6

Categories