How to compile this C code to WebAssembly correctly? - javascript

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;
}

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 print array of numbers out in tabular format

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);
}
}

finding number of changes to make 2 strings anagram

I want to find the minimum number of characters of the first string that needs to be changed to enable me to make it an anagram of the second string.
1st problem it always return -1
function anagram(s) {
if (s % 2 == 0) {
var len = s.legnth;
var diff = [];
for (var x = 0; x < len / 2; x++) {
var y = s[x]++;
}
for (var x = len / 2; x < s.legnth; x++) {
var z = s[x]++;
}
y = y.sort().splice(",").tostring();
z = y.sort().splice(",").tostring();
for (var x = 0; i < z.length; x++) {
if (y[x] != z[x]) {
diff.push(y[x]);
}
}
return diff.length;
} else {
return -1;
}
}
function main() {
var q = parseInt(readLine());
for (var a0 = 0; a0 < q; a0++) {
var s = readLine();
var result = anagram(s);
process.stdout.write("" + result + "\n");
}
}

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;

Got 90% of the JavaScript code - can't figure out the rest

So I am trying to model Gram-Schmidt for any size N×N matrix, and I have officially hit a roadblock I can't get past. I know it's a matter of looping this correctly, but I can't figure out what the problem is. Remember I do not want to just pass in a 3×3 matrix, but any size N×N.
The course notes QR Decomposition with Gram-Schmidt explains exactly what I want to do. Very simple calculation by the way. In the course notes ||u|| means that it is the sum of the square of the elements, so sqrt(x12 + x22 + x32 + .... + xn2).
The multiplication symbol is actually the dot product.
The code I wrote so far is listed below. What is wrong with it?
function qrProjection(arr) {
var qProjected = [];
var tempArray = [];
var aTemp = arr;
var uTemp = new Array(arr.length);
var uSquareSqrt = new Array(arr.length);
var eTemp = [];
var sum = 0;
var sumOfSquares = 0;
var breakCondition = 0;
var secondBreakCondition = 0;
var iterationCounter = 0;
//Build uTemp Array
for (i = 0; i < arr.length; i++) {
uTemp[i] = new Array(arr[i].length);
}
for (i = 0; i < arr.length; i++) {
eTemp[i] = new Array(arr[i].length);
}
uTemp[0] = aTemp[0];
for (j = 0; j <= arr.length; j++) {
for (l = 0; l < arr[j].length; l++) {
if (breakCondition == 1) break;
sumOfSquares = Math.pow(uTemp[j][l], 2) + sumOfSquares;
}
if (breakCondition == 0) {
uSquareSqrt[j] = Math.sqrt(sumOfSquares);
sumOfSquares = 0;
}
for (i = 0; i < arr[j].length; i++) {
if (breakCondition == 1) break;
eTemp[j][i] = (1 / (uSquareSqrt[j])) * (uTemp[j][i]);
}
breakCondition = 1;
if (iterationCounter == 0) {
for (m = 0; m < arr[j].length; m++) {
matrixDotProduct = aTemp[j + 1][m] * eTemp[j][m] + matrixDotProduct;
}
}
else {
for (m = 0; m < arr[j].length; m++) {
for (s = 0; s <= iterationCounter; s++) {
matrixDotProduct = aTemp[j + 1][s] * eTemp[m][s] + matrixDotProduct;
}
for (t = 0; t < arr[j].length; t++) {
uTemp[j + 1][t] = aTemp[j + 1][t] - eTemp[j][t] * matrixDotProduct;
}
}
}
if (iterationCounter == 0) {
for (m = 0; m < arr[j].length; m++) {
uTemp[j + 1][m] = aTemp[j + 1][m] - eTemp[j][m] * matrixDotProduct;
}
}
matrixDotProduct = 0;
for (l = 0; l < arr[j].length; l++) {
sumOfSquares = Math.pow(uTemp[j + 1][l], 2) + sumOfSquares;
}
uSquareSqrt[j + 1] = Math.sqrt(sumOfSquares);
sumOfSquares = 0;
for (i = 0; i < arr[j].length; i++) {
eTemp[j + 1][i] = (1 / (uSquareSqrt[j + 1])) * (uTemp[j + 1][i]);
}
iterationCounter++;
}
qProjected = eTemp;
return qProjected;
}
I must apologize that instead of tweaking your code, I wrote my own from scratch:
/* Main function of interest */
// Each entry of a matrix object represents a column
function gramSchmidt(matrixA, n) {
var totalVectors = matrixA.length;
for (var i = 0; i < totalVectors; i++) {
var tempVector = matrixA[i];
for (var j = 0; j < i; j++) {
var dotProd = dot(matrixA[i], matrixA[j], n);
var toSubtract = multiply(dotProd, matrixA[j], n);
tempVector = subtract(tempVector, toSubtract, n);
}
var nrm = norm(tempVector, n);
matrixA[i] = multiply(1 / nrm, tempVector, n);
}
}
/*
* Example usage:
* var myMatrix = [[1,0,0],[2,3,0],[5,4,7]];
* gramSchmidt(myMatrix, 3);
* ==> myMatrix now equals [[1,0,0],[0,1,0],[0,0,1]]
* 3 here equals the number of dimensions per vector
*/
/* Simple vector arithmetic */
function subtract(vectorX, vectorY, n) {
var result = new Array(n);
for (var i = 0; i < n; i++)
result[i] = vectorX[i] - vectorY[i];
return result;
}
function multiply(scalarC, vectorX, n) {
var result = new Array(n);
for (var i = 0; i < n; i++)
result[i] = scalarC * vectorX[i];
return result;
}
function dot(vectorX, vectorY, n) {
var sum = 0;
for (var i = 0; i < n; i++)
sum += vectorX[i] * vectorY[i];
return sum;
}
function norm(vectorX, n) {
return Math.sqrt(dot(vectorX, vectorX, n));
}
Note that the algorithm above computes the Gram-Schmidt orthogonalization, which is the matrix [e1 | e2 | ... | en], not the QR factorization!

Categories