Merge Function for two arrays, The function is not working properly and doesn't give the required answer. I want that the sorted arrays are merged up as it is the function saying, but it doesn't work.
var Merge = function(array,array1,array2)
{
var n_array = array.length;
var n_array1 = array1.length;
var i = j = k = 0;
while(i < n_array && j < n_array1)
{
if(array[i] <= array2[j])
{
array2[k] = array[i];
i = i + 1;
}
else
{
array2[k] = array1[j];
j = j + 1;
}
k = k + 1;
}
while(i < n_array)
{
array2[k] = array[i];
i = i + 1;
k = k + 1;
}
while(j < n_array1)
{
array2[k] = array1[j];
j = j + 1;
k = k + 1;
}
return array2;
};
array = [1,3,5,7];
array1 = [2,4,6,8];
array2 = [];
var result = Merge(array,array1,array2);
console.log("The array is sorted is " + result);
Why my code give an answer:
The array is sorted is 2,4,6,8,1,3,5,7
var Merge = function(array,array1,array2)
{
var n_array = array.length;
var n_array1 = array1.length;
var i = j = k = 0;
while(i < n_array && j < n_array1)
{
if(array[i] <= array1[j])
{
array2[k] = array[i];
i = i + 1;
}
else
{
array2[k] = array1[j];
j = j + 1;
}
k = k + 1;
}
while(i < n_array)
{
array2[k] = array[i];
i = i + 1;
k = k + 1;
}
while(j < n_array1)
{
array2[k] = array1[j];
j = j + 1;
k = k + 1;
}
return array2;
};
array = [1,3,5,7];
array1 = [2,4,6,8];
array2 = [];
var result = Merge(array,array1,array2);
console.log("The array is sorted is " + result);
It Works :)
This is the edited solution to the OP's problem.
While the fix for your code is mentioned above, that is a lot of lines for just doing a merge and sort. If you know you will be dealing with numbers you could use the following:
var arr = [1, 10, 22];
var arr1 = [20, 17, 3];
var arr2 = arr.concat(arr1);
sortAsc(arr2);
function sortAsc(arrayToSort){
return arrayToSort.sort(function(a, b){
return a - b;
});
}
Related
I'm calling a function using the setTimeout() function from a recursive function, however increasing the timeout time doesn't bring any change to the speed of the execution.
I was trying to implement Mergesort, the merger() function recursively calls itself and also calls another function Merge() using SetTimeout() but no matter how large I set the timeout interval to be, the execution takes place at the same speed.
I found several previous questions on setTimeout not working, (I came across a way to multiply for loop's variable with the time interval, How can I do something like that here?) but I'm a beginner in development and react and couldn't connect them to this, I'd like to know why exactly it is happening.
This is the problem area.
function merger(l,r){
if(l>=r){
return;//returns recursively
}
var m =l+ parseInt((r-l)/2);
merger(l,m);
merger(m+1,r);
setTimeout(merge,10,l,m,r)
}
More detailed code
import { useState } from "react";
function Visualiser () {
const [array,setarray] = useState([]);
const gendivs = () => {
var nums = [];
for (let i=0; i<250; i++ ){
let x = Math.floor(Math.random()*600 + 10);
nums[i] = x;
}
setarray(nums)
}
const merge = (l,m,r) => {
setTimeout(()=>{
setarray((prev) => {
const arr = [...prev]
var n1 = m - l + 1;
var n2 = r - m;
// Create temp arrays
var L = [];
var R = [];
for (let i = 0; i < n1; i++){
L[i] = arr[l + i];
}
for (let j = 0; j < n2; j++) {
R[j] = arr[m + 1 + j];
}
// Copy data to temp arrays L[] and R[]
// Merge the temp arrays back into arr[l..r]
// Initial index of first subarray
var i = 0;
// Initial index of second subarray
var j = 0;
// Initial index of merged subarray
var k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
return arr;
})
}, 10)
}
function merger(l,r){
if(l>=r){
return;//returns recursively
}
var m =l+ parseInt((r-l)/2);
merger(l,m);
merger(m+1,r);
setTimeout(merge,10,l,m,r)
}
function mergeSort () {
let l = 0;
let r = 249;
merger(l,r);
}
const selectsort = () => {
let t = [...array]
// One by one move boundary of unsorted subarray
for (let i = 0; i < 250; i++)
{
// Find the minimum element in unsorted array
let idx = i;
for (let j = i + 1; j < 250; j++) {
if (t[j] < t[idx])
idx = j;
}
var temp1 = t[i];
t[i] = t[idx];
t[idx] = temp1
// Swap the found minimum element with the first element
setTimeout(()=> {
setarray( (prev) => {
let arr = [...prev]
const temp = arr[i]
arr[i] = arr[idx]
arr[idx] = temp
return arr
})
},i*50)
}
}
const divs = array.map((ar, index) =>{
const h = ar.toString()+ "px"
return <div key={index} style = {{backgroundColor:"turquoise", margin: "1px", height: h, width: "3px"}}></div>
})
return (
<div>
<div className="btns">
<button onClick={gendivs}> Generate Array </button>
<button onClick={selectsort}> Selection Sort</button>
<button onClick={mergeSort}> Merge Sort</button>
</div>
<div className="d"> {divs} </div>
</div>
);
}
export default Visualiser;
ArrayList1 = [a,b,c,d]
ArrayList1 = [d,c,e,f,g]
I would like to have result as
ArrayListFinal = [c,d]
How can I accomplish this?
try this...........
for(int i =0;i<list1.size();i++){
for(int j=0;j<list2.size();j++){
if(list.get(j).equals(list2.get(i))){
listfinal.add(list.get(i));
}
}
}
for(int i=0;i<listfinal.size();i++){
System.out.println(list1.get(i));
}
Your problem is to find the intersection (denoted as ∩) of two array A and B .
Suppose the arrays are unsorted. The simplest way is to compare the elements one by one, like this:
function getIntersect(arr1, arr2) {
var temp = [];
for(var i = 0; i < arr1.length; i++){
for(var k = 0; k < arr2.length; k++){
if(arr1[i] == arr2[k]){
temp.push( arr1[i]);
break;
}
}
}
return temp;
}
But if the arr2 is much shorter than arr1, you may using a hash table to speed up:
function getIntersect(arr1, arr2) {
var r = [], o = {}, l = arr2.length, i, v;
for (i = 0; i < l; i++) {
o[arr2[i]] = true;
}
l = arr1.length;
for (i = 0; i < l; i++) {
v = arr1[i];
if (v in o) {
r.push(v);
}
}
return r;
}
I have following array:
Point[][] points;
It is initialized using other array that contains null values.
What I want is to delete null cells, so the new array will not contain any null values.
For example:
Other Array: P, P, P
P, P, P
N, P, N
N, P, N
New Array: P, P, P
P, P, P
P,
P,
How can I achieve it?
Update:
Is it good way to do it?
Point[][] temp = cv.getPtStroke();
int i = 0;
int j = 0;
for (; i < temp.length && temp[i]!= null; i++) {}
Point[][] temp1 = new Point[i][];
i = 0;
for (; i < temp.length && temp[i]!= null; i++)
{
for (; j < temp[i].length && temp[i][j]!= null; j++){}
temp1[i] = new Point[j];
}
Update:
Problem Solved:
Point[][] temp = cv.getPtStroke();
int i = 0;
for (; i < temp.length && temp[i]!= null; i++) {}
Point[][] temp1 = new Point[i][];
i = 0;
for (; i < temp.length && temp[i]!= null; i++)
{
int j = 0;
for (; j < temp[i].length && temp[i][j]!= null; j++){}
temp1[i] = new Point[j];
}
int k = 0;
int temp1XSize = temp1.length;
int temp1YSize = 0;
for (; k < temp1XSize; k++)
{
temp1YSize = temp1[k].length;
int l = 0;
for (; l < temp1YSize; l++){
temp1[k][l] = temp[k][l];
}
}
Do you know any better method?
If you work with Array in major case - this impossible. Array have "fix" size. But in some programming language it is possible by using ArrayList, List, HasTable and etc entities.
For example in PHP Arrays wor like ArrayList (or List). In JavaScript you may use object instead of array.
Example for PHP:
//Origin Array
$array = array(
array(1,2,3),
array(null,2, null),
array(null,2,null),
);
// New array
$result = array();
foreach ($array as $i => $row) {
$result[$i] = array();
foreach ($array[$i] as $j => $cell) {
if ($cell !== null) {
$result[$i][$j] = $cell;
}
}
}
Code for JavaScript:
var array = [
[1,2,3],
[null,2,null],
[null,2,null]
];
var result = {};
for (var i = 0; i < array.length; i++ ) {
result[i] = {};
for (var j = 0; j < array[i].length; j++ ) {
if (array[i][j] !== null) {
result[i][j] = array[i][j];
}
}
}
I have an array:
var exArr:Array = [5,6,10,6,5,11,7,9,12,8,8,13,7,9,14];
I want to array:
var resultArr:Array = [5,6,7,8,9,10,11,12,13,14];
This may use full to you.
var a:Array = [5,6,10,6,5,11,7,9,12,8,8,13,7,9,14];
a.sort();
var i:int = 0;
while(i < a.length) {
while(i < a.length+1 && a[i] == a[i+1]) {
a.splice(i, 1);
}
i++;
}
for other, see here
Try this:
var exArr:Array = [5,6,10,6,5,11,7,9,12,8,8,13,7,9,14];
function group(subject:Array):Array
{
var base:Array = subject.slice().sort(Array.NUMERIC);
var prev:Number = base[0];
for(var i:int = 1; i < base.length; i++)
{
if(base[i] === prev)
{
base.splice(i, 1);
i--;
}
prev = base[i];
}
return base;
}
trace( group(exArr) );
Given a 2D NxN matrix, visualize it as concentric circles. You have to find the rotated matrix where each element in the circle is rotated by 1 position layer by layer in an alternate clockwise and anticlockwise direction. All rotations should be in-place.
2 3 4 5
1 6 7 8
4 2 1 9
5 3 2 4
should get transformed to
1 2 3 4
4 7 1 5
5 6 2 8
3 2 4 9
I thought about the solution
1> For clockwise circle rotation, read elements in the order
i -> 0 to n-1 and j = 0
j -> 0 to n-1 and i = n-1
i -> n-1 to 0 and j = n-1
j -> n-1 to 0 and i = 0
2> For anti-clockwise circle rotation, read elements in the order
j -> 0 to n-1 and i = 0
i -> 0 to n-1 and j = n-1
j -> n-1 to 0 and i = n-1
i -> n-1 to 0 and j = 0
Code
for(int cnt = 0; cnt < n/2; cnt++)
{
if(cnt%2 == 0) // Clockwise
{
i = cnt; j = cnt;
// while loops for each case
}
else // anti-clockwise
{
i = cnt; j = cnt;
// while loops for each case
}
}
Is there any better approach to solve this problem in O(n2) or better ?
As your array is of size N*N and the desired computation demands each element to be visited atleast once, there cannot be a solution better than O(n^2) which uses 2 dimensional arrays.
I think that your solution will be fine if the operation has to be done single time on the same array.
If you have to do this operation multiple times on the same input array, better create circles from the input array. The data structure of circle should be a CLL (circular linked list). So doing the operation multiple times will be piece of cake as you have to change the root element of the CLL storing the circle info depending on the direction.
I think that this can be solved easily in-place in O(n) time.
(NOTE: O(N) where N is the total number of matrix elements)
The following solution doesn't use four consecutive loops, but uses a small table of [X, Y] deltas that describe the difference between the current coordinate and the next one, when the next coordinate is invalid (i.e outside of the current window) the index to the table itself is advanced and the look-up repeated. The algorithm starts with full window and decreases it by one element from each side every time the nested loop finishes. The whole process repeats until the window defined as [minX, minY, maxX, maxY] is valid (i.e. contains at least 2x2 elements).
This solution doesn't implement swapping cw and ccw, but this is the easiest part to add.
function pad(s, n) {
while(s.length < n)
s = " " + s;
return s;
}
// Create a matrix of [WxH] size.
function Matrix(w, h, data) {
if (Array.isArray(data)) {
if (data.length !== w * h)
throw new Error("Data.length has to match the size " + (w * h) + ".");
}
else {
var n = typeof data === "number" ? data : 0.0;
data = [];
for (var i = 0; i < w*h; i++) data.push(n);
}
this.w = w;
this.h = h;
this.data = data;
}
// Get value at [x, y]
Matrix.prototype.get = function(x, y) {
if (x < 0 || x >= this.w || y < 0 || y >= this.h)
throw new Error("Index [" + x + ", " + y + "] out of bounds");
return this.data[y * this.w + x];
}
// Set value at [x, y] and return the previous value.
Matrix.prototype.set = function(x, y, value) {
if (x < 0 || x >= this.w || y < 0 || y >= this.h)
throw new Error("Index [" + x + ", " + y + "] out of bounds");
var i = y * this.w + x;
var prev = this.data[i];
this.data[i] = value;
return prev;
}
// Log the matrix data.
Matrix.prototype.dump = function() {
var s = "["
var i = 0;
for (var y = 0; y < this.h; y++) {
for (var x = 0; x < this.w; x++, i++) {
s += pad("" + this.data[i], 2);
if (x !== this.w - 1)
s += ","
}
if (y !== this.h - 1)
s += ",\n ";
}
s += "]";
console.log(s);
}
// Shift, `dir` can be "cw" or "ccw".
Matrix.prototype.shift = function(dir) {
var instructions = {
cw : [1, 0, 0, 1,-1, 0, 0,-1],
ccw: [0, 1, 1, 0, 0,-1,-1, 0]
};
var inst = instructions[dir];
// A window, shrink by one from each side after the nested loop is done.
var minX = 0;
var minY = 0;
var maxX = this.w - 1;
var maxY = this.h - 1;
while (minX < maxX && minY < maxY) {
// Always start at the top-left corner and iterate.
var x0 = minX;
var y0 = minY;
var v0 = this.get(x0, y0);
var n = 0;
for (;;) {
var x1 = x0 + inst[n + 0];
var y1 = y0 + inst[n + 1];
if (x1 < minX || x1 > maxX || y1 < minY || y1 > maxY) {
n += 2;
x1 = x0 + inst[n + 0];
y1 = y0 + inst[n + 1];
}
v0 = this.set(x1, y1, v0);
// Last one.
if (x1 === minX && y1 === minY)
break;
x0 = x1;
y0 = y1;
}
minX++;
minY++;
maxX--;
maxY--;
}
}
var a = new Matrix(3, 3, [
1,2,3,
4,5,6,
7,8,9,
]);
a.dump();
a.shift("cw");
a.dump();
var b = new Matrix(4, 4, [
1 ,2 ,3 ,4 ,
5 ,6 ,7 ,8 ,
9 ,10,11,12,
13,14,15,16
]);
b.dump();
b.shift("ccw");
b.dump();
I faced this problem recently in a job interview and I failed to solve it in under one hour.
Then I got home and produced the code below in java. It is recursive and I believe it has O(n^2) complexity. You can also see the code here: https://github.com/lotif/rotateMatrix
You will have first to input the dimension of the (square) matrix and then the numbers of the matrix itself separated by spaces, line by line. For instance:
3
1 2 3
4 5 6
7 8 9
It will return you the matrix rotated clockwise in concentric circles.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class RotateMatrix {
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
int d = s.nextInt();
int[][] matrix = new int[d][d];
for(int i = 0; i < d; i++) {
for(int j = 0; j < d; j++) {
matrix[i][j] = Integer.parseInt(s.next());
}
}
matrix = rotate(matrix);
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix.length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
s.close();
}
public static int[][] rotate(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix.length == 1) {
return matrix;
}
List<Integer> outerCircle = getOuterCircle(matrix);
matrix = removeOuterCircle(matrix);
//rotating outer circle
outerCircle.add(0, outerCircle.remove(outerCircle.size() - 1));
matrix = rotate(matrix);
matrix = addOuterCircle(outerCircle, matrix);
return matrix;
}
private static int[][] addOuterCircle(List<Integer> outerCircle, int[][] matrix) {
int d = matrix.length + 2;
int[][] newMatrix = new int[d][d];
//Adding the outer circle to the matrix
for(int j = 0; j < d; j++) {
newMatrix[0][j] = outerCircle.remove(0);
}
for(int i = 1; i < d; i++) {
newMatrix[i][d-1] = outerCircle.remove(0);
}
for(int j = d-2; j >= 0; j--) {
newMatrix[d-1][j] = outerCircle.remove(0);
}
for(int i = d-2; i >= 1; i--) {
newMatrix[i][0] = outerCircle.remove(0);
}
//Adding the inner matrix
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
newMatrix[i + 1][j + 1] = matrix[i][j];
}
}
return newMatrix;
}
private static List<Integer> getOuterCircle(int[][] matrix) {
int d = matrix.length;
List<Integer> outerCircle = new ArrayList<Integer>();
for(int j = 0; j < d; j++) {
outerCircle.add(matrix[0][j]);
}
for(int i = 1; i < d; i++) {
outerCircle.add(matrix[i][d-1]);
}
for(int j = d-2; j >= 0; j--) {
outerCircle.add(matrix[d-1][j]);
}
for(int i = d-2; i >= 1; i--) {
outerCircle.add(matrix[i][0]);
}
return outerCircle;
}
private static int[][] removeOuterCircle(int[][] matrix) {
int d = matrix.length;
int[][] newMatrix = new int[d-2][d-2];
for(int i = 1; i < d-1; i++) {
for(int j = 1; j < d-1; j++) {
newMatrix[i-1][j-1] = matrix[i][j];
}
}
return newMatrix;
}
}
public class ShiftArray {
static void shiftArray(int[][]a, int index, int n) {
if ((n%2 == 0) && (index >= n/2))
return;
if ((n%2 != 0) && (index > n/2))
return;
int tempRowTopLast = a[index][n-1-index];
int tempColRightLast = a[n-1-index][n-1-index];
int tempRowBottomLast = a[n-1-index][index];
int tempColLeftLast = a[index][index];
int temp, temp2;
temp = tempColLeftLast;
for (int k = index + 1; k < n-index; k++) {
temp2 = a[index][k];
a[index][k] = temp;
temp = temp2;
}
temp = tempRowTopLast;
for (int k = index + 1; k < n-index; k++) {
temp2 = a[k][n-1-index];
a[k][n-1-index] = temp;
temp = temp2;
}
temp = tempColRightLast;
for (int k = n-2-index; k >=index; k--) {
temp2 = a[n-1-index][k];
a[n-1-index][k] = temp;
temp = temp2;
}
temp = tempRowBottomLast;
for (int k = n-2-index; k >=index; k--) {
temp2 = a[k][index];
a[k][index] = temp;
temp = temp2;
}
shiftArray(a, index+1, n);
}
public static void main(String[] args) {
int a[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
shiftArray(a, 0, 3);
System.out.println("Rotated array...");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + ",");
}
System.out.println();
}
}
}
import java.util.Scanner;
public class RotateMatrix
{
static int rows = 0;
static int cols = 0;
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
rows = scan.nextInt();
cols = scan.nextInt();
int rots = scan.nextInt();
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i][j] = scan.nextInt();
}
}
for (int i = 0; i < rots; i++)
rotate(matrix, 0, rows - 1, 0, cols - 1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
scan.close();
}
public static int[][] rotate(int[][] arr, int rowStart, int rowEnd, int colStart, int colEnd)
{
if (rowStart == rowEnd && colStart == colEnd)
{
return arr;
}
if (rowStart > rowEnd || colStart > colEnd)
{
return arr;
}
int temp = arr[rowStart][colStart];
for (int j = colStart; j < colEnd; j++)
{
arr[colStart][j] = arr[colStart][j + 1];
}
for (int i = rowStart; i < rowEnd; i++)
{
arr[i][colEnd] = arr[i + 1][colEnd];
}
for (int i = colEnd; i > colStart; i--)
{
arr[rowEnd][i] = arr[rowEnd][i - 1];
}
for (int i = rowEnd; i > rowStart; i--)
{
arr[i][colStart] = arr[i - 1][colStart];
}
if (rows == 1)
{
arr[colEnd][rowStart] = temp;
}
else
arr[rowStart + 1][colStart] = temp;
System.out.println("-----------------------------------------\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println("-----------------------------------------\n");
rotate(arr, rowStart + 1, rowEnd - 1, colStart + 1, colEnd - 1);
return arr;
}
}
Clockwise rotation by 90 degrees. O(n^2) time and O(1) memory in Python3:
# #param A : list of list of integers
# #return the same list modified
def rotate(A):
for row in range(len(A) // 2):
for col in range(row, len(A)-1 - row): # First col already takes care of last.
r = row
c = col
tmp1 = A[r][c]
while True:
next_r = c
next_c = len(A) - 1 - r
tmp2 = A[next_r][next_c]
A[next_r][next_c] = tmp1
if next_r == row and next_c == col:
break
tmp1 = tmp2
r = next_r
c = next_c
return A