Delete null values (cells) from 2 dimensional array - arrays

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

Related

C Program numbers not sorting array correctly

I have an array of structs for products that I am trying to sort by name, type, price, and quantity. Name and type work, but price and quantity aren't working.
My code is:
else if (sort == sortByPrice)
{
for (int i = 0; i < numProducts; i++)
{
int smallPosition = i;
for (int x = i + 1; x < numProducts; x++)
{
if (list[i].price > list[x].price)
{
smallPosition = x;
}
}
temp = list[i];
list[i] = list[smallPosition];
list[smallPosition] = temp;
}
}
else if (sort == sortByQty)
{
for (int i = 0; i < numProducts; i++)
{
int smallPosition = i;
for (int x = i + 1; x < numProducts; x++)
{
if (list[i].qty > list[x].qty)
{
smallPosition = x;
}
}
temp = list[i];
list[i] = list[smallPosition];
list[smallPosition] = temp;
}
}
Can anyone tell me why it doesn't work/how to fix it?
Following up on Lee Daniel Crocker's comment, you should dynamically compare with the value at smallPosition instead of i so that it will always point to the smallest remaining item:
int smallPosition = i;
for (int x = i + 1; x < numProducts; x++)
{
if (list[smallPosition].price > list[x].price)
{
smallPosition = x;
}
}
You should move the swap code inside the if statement:
for (int i = 0; i < numProducts; i++)
{
for (int x = i + 1; x < numProducts; x++)
{
if (list[i].price > list[x].price)
{
temp = list[i];
list[i] = list[X];
list[X] = temp;
}
}
}
Just use bubble sort.
In the bubble sort you swap the values of the current value is bigger than the next one, if you do this action until you get to the end of the array then the array will be sorted.

gridview dataitem to decimal array

enter code hereHello I try to convert the dataitem into decimal array, here is my code;
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (; i < 9; )
{
if (!DBNull.Value.Equals(DataBinder.Eval(e.Row.DataItem, headerNames[i])))
TotalSales += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, headerNames[i]));
totals(e.Row.DataItem);
}
}
}
public static decimal[] totals(object arr)
{
decimal[] res = arr as decimal[];
decimal[] sRes = res.OfType<decimal>().ToArray();
return sRes;
}
I can see that the dataitem successfully assigned to arr.
However the line
decimal[] res = arr as decimal[]; does not assign the arr to res, so the next line gives me an error complaining the value cannot be null.
Can you please help?
While I was waiting for an answer here, I tried and came up with a code that calculates totals in GridView_DataBound event, please comment if there is anything can be better and how to not show the total (0.0) under the columns that do not have decimal values (i.e. string)
public static void gridViewTotals1(object sender , EventArgs e)
{
var grdview = (GridView)sender;
decimal[,] rowAndColumns = new decimal[grdview.Rows.Count, grdview.Columns.Count];
decimal n;
decimal[] totalSalesArray = new decimal[grdview.Columns.Count];
for (int i = 0; i < grdview.Columns.Count; i++)
{
for (int j = 0; j < grdview.Rows.Count; j++)
if (decimal.TryParse(grdview.Rows[j].Cells[i].Text, out n))
{
rowAndColumns[j, i] = Convert.ToDecimal(grdview.Rows[j].Cells[i].Text);
}
}
GridViewRow footerRow = grdview.FooterRow;
for (int k = 0; k < grdview.Columns.Count; k++)
{
decimal totalSales = 0;
for (int l = 0; l < grdview.Rows.Count; l++)
{
totalSales += rowAndColumns[l, k];
totalSalesArray[k] = totalSales;
footerRow.Cells[k].Text = String.Format("{0:N2}", totalSales);
}
}
}

Array index out of bounds in sieve of eratosthenes

I am having trouble with ArrayIndexOutOfBounds.
I am new to coding and I don't fully understand this problem and I am unable to fix it. Any help is appreciated.
public class Primes {
public static void main(String[] args) {
final int SIZE = 10000;
boolean[] numberIsPrime = new boolean[SIZE];
int rowCounter = 0;
for( int index = 1; index <= SIZE; index++) {
numberIsPrime[index] = true;
}
for( int index = 2; index <= SIZE; index++) {
if( numberIsPrime[index] = true){
for( int i = index; i <= SIZE; i++){
numberIsPrime[index * i] = false;
}
}
}
for( int index = 1; index <= SIZE; index++){
if( numberIsPrime[index] = true){
System.out.println(index + " ");
rowCounter++;
if( rowCounter == 10){
System.out.println();
}
}
}
}
}
You should tag the question with the language you're using, but I'm gonna assume it's Java. The problem is
boolean[] numberIsPrime = new boolean[SIZE];
...
for( int index = 1; index <= SIZE; index++) {
numberIsPrime[index] = true;
}
The first line declares numberIsPrime as an array of size 10000. That means you can access numberIsPrime[0], numberIsPrime[1], ... numberIsPrime[9999]. You can't access numberIsPrime[10000].

I want to collect the common elements in two different arraylist

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

Rotate a 2D NxN matrix in Concentric Circles

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

Resources