/**
 * Analyzes the randomness quality of a binary string using multiple metrics
 * @param {string} binaryString - String of 1s and 0s to analyze
 * @returns {Object} Analysis results with various randomness metrics
 */
function analyzeRandomness(binaryString) {
    if (!/^[01]+$/.test(binaryString)) {
        throw new Error('Input must contain only 1s and 0s');
    }

    const length = binaryString.length;
    const results = {};

    // 1. Basic proportion analysis
    const countOnes = (binaryString.match(/1/g) || []).length;
    const proportionOnes = countOnes / length;
    const proportionZeros = 1 - proportionOnes;
    
    results.basicProportions = {
        proportionOnes,
        proportionZeros,
        deviation: Math.abs(0.5 - proportionOnes), // Deviation from perfect 50/50
        isBalanced: Math.abs(0.5 - proportionOnes) < 0.1 // Within 10% of 50/50
    };

    // 2. Runs analysis (consecutive sequences)
    const runs = binaryString.match(/(.)\1*/g) || [];
    const runLengths = runs.map(run => run.length);
    
    results.runsAnalysis = {
        totalRuns: runs.length,
        averageRunLength: runLengths.reduce((a, b) => a + b, 0) / runs.length,
        maxRunLength: Math.max(...runLengths),
        runLengthDistribution: runLengths.reduce((acc, len) => {
            acc[len] = (acc[len] || 0) + 1;
            return acc;
        }, {})
    };

    // 3. Entropy calculation (Shannon entropy)
    const entropy = -[proportionOnes, proportionZeros].reduce((sum, p) => {
        return sum + (p === 0 ? 0 : p * Math.log2(p));
    }, 0);
    
    results.entropy = {
        value: entropy,
        normalized: entropy / Math.log2(2), // Normalized to [0,1]
        isHighEntropy: entropy > 0.9 // Threshold for high entropy
    };

    // 4. Autocorrelation analysis
    const autocorrelations = [];
    for (let lag = 1; lag <= Math.min(20, Math.floor(length / 2)); lag++) {
        let correlation = 0;
        for (let i = 0; i < length - lag; i++) {
            correlation += (binaryString[i] === binaryString[i + lag]) ? 1 : -1;
        }
        autocorrelations.push(correlation / (length - lag));
    }
    
    results.autocorrelation = {
        values: autocorrelations,
        hasSignificantPatterns: autocorrelations.some(val => Math.abs(val) > 0.2)
    };

    // 5. Frequency analysis of n-grams (pairs and triples)
    const analyzeNGrams = (n) => {
        const ngrams = {};
        const expected = 1 / Math.pow(2, n);
        
        for (let i = 0; i <= length - n; i++) {
            const gram = binaryString.slice(i, i + n);
            ngrams[gram] = (ngrams[gram] || 0) + 1;
        }
        
        const frequencies = Object.entries(ngrams).map(([gram, count]) => ({
            gram,
            frequency: count / (length - n + 1),
            deviation: Math.abs(count / (length - n + 1) - expected)
        }));
        
        return {
            frequencies,
            maxDeviation: Math.max(...frequencies.map(f => f.deviation)),
            averageDeviation: frequencies.reduce((sum, f) => sum + f.deviation, 0) / frequencies.length
        };
    };
    
    results.nGramAnalysis = {
        pairs: analyzeNGrams(2),
        triples: analyzeNGrams(3)
    };

    // 6. Overall randomness score (0-1)
    const calculateScore = () => {
        const weights = {
            proportion: 0.2,
            entropy: 0.3,
            autocorrelation: 0.2,
            nGrams: 0.3
        };

        const scores = {
            proportion: 1 - (results.basicProportions.deviation * 2),
            entropy: results.entropy.normalized,
            autocorrelation: results.autocorrelation.hasSignificantPatterns ? 0.5 : 1,
            nGrams: 1 - ((results.nGramAnalysis.pairs.maxDeviation + 
                         results.nGramAnalysis.triples.maxDeviation) / 2)
        };

        return Object.entries(weights).reduce((score, [key, weight]) => {
            return score + (scores[key] * weight);
        }, 0);
    };

    results.overallScore = calculateScore();

    return results;
}

// Example usage and interpretation
function interpretRandomness(binaryString) {
    const analysis = analyzeRandomness(binaryString);
    
    return {
        score: analysis.overallScore,
        interpretation: {
            quality: analysis.overallScore > 0.8 ? "High" : 
                     analysis.overallScore > 0.6 ? "Moderate" : "Low",
            issues: [
                !analysis.basicProportions.isBalanced && 
                    "Unbalanced distribution of 1s and 0s",
                analysis.entropy.value < 0.9 && 
                    "Low entropy indicating potential predictability",
                analysis.autocorrelation.hasSignificantPatterns && 
                    "Contains repeating patterns",
                analysis.nGramAnalysis.pairs.maxDeviation > 0.1 && 
                    "Uneven distribution of bit pairs"
            ].filter(Boolean)
        }
    };
}
// First include the full analyzer functions from before
const testSequence = "11010011011110001011011001101011001010001101111010010011110001110100101";

// Run the analysis
const analysis = analyzeRandomness(testSequence);
const interpretation = interpretRandomness(testSequence);

// Display results
console.log("Analysis Results for:", testSequence);
console.log("Length:", testSequence.length);
console.log("\nBasic Proportions:");
console.log("----------------");
console.log(`Ones: ${(analysis.basicProportions.proportionOnes * 100).toFixed(2)}%`);
console.log(`Zeros: ${(analysis.basicProportions.proportionZeros * 100).toFixed(2)}%`);
console.log(`Deviation from 50/50: ${(analysis.basicProportions.deviation * 100).toFixed(2)}%`);

console.log("\nRuns Analysis:");
console.log("-------------");
console.log(`Total runs: ${analysis.runsAnalysis.totalRuns}`);
console.log(`Average run length: ${analysis.runsAnalysis.averageRunLength.toFixed(2)}`);
console.log(`Maximum run length: ${analysis.runsAnalysis.maxRunLength}`);
console.log("\nRun length distribution:");
console.log(analysis.runsAnalysis.runLengthDistribution);

console.log("\nEntropy:");
console.log("--------");
console.log(`Raw entropy: ${analysis.entropy.value.toFixed(4)}`);
console.log(`Normalized entropy: ${analysis.entropy.normalized.toFixed(4)}`);

console.log("\nN-Gram Analysis:");
console.log("--------------");
console.log("Pair frequencies:");
analysis.nGramAnalysis.pairs.frequencies.forEach(f => {
    console.log(`${f.gram}: ${(f.frequency * 100).toFixed(2)}% (deviation: ${(f.deviation * 100).toFixed(2)}%)`);
});

console.log("\nOverall Assessment:");
console.log("-----------------");
console.log(`Randomness Score: ${(analysis.overallScore * 100).toFixed(2)}%`);
console.log(`Quality Rating: ${interpretation.interpretation.quality}`);

if (interpretation.interpretation.issues.length > 0) {
    console.log("\nPotential Issues:");
    interpretation.interpretation.issues.forEach(issue => console.log(`- ${issue}`));
}
 

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

Syntax help

STDIN Example

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log("Hello, " + line);
});

variable declaration

KeywordDescriptionScope
varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned, it can not be modifiedGlobal or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log(mobiles[0]);

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

() => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                    .map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest(...) operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread(...) operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
  console.log(`Hello ${name}!`);
}
 
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if(condition){
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if(condition){
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch(condition){
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while (condition); 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor() { ... } //Mandatory Class method
  method1() { ... }
  method2() { ... }
  ...
}

Example:

class Mobile {
  constructor(model) {
    this.name = model;
  }
}

mbl = new Mobile("iPhone");