Get Positive Bits Indexes from Bit Array - asp.net

Say I have the following BitArray combinedResults = searchBitArray.And(genreBitArray);
Which contains positive bits i.e 100100110000
How can I get the indexes of all the positive ones ?

Here's a first, decidedly ghetto, crack at it:
BitArray ba = new BitArray(new bool[] {true,false,false,true,false,false,true,true,false,false,false,false});
List<int> pos = new List<int>();
for (int i = 0; i < ba.Length; i++)
{
if (ba[i])
pos.Add(i);
}
That would give you a list containing 0, 3, 6, 7. You could start at ba.Length - 1 and decrement down to zero if you need to read from right to left.
edit: Wrapped in an extension method, just because:
void Main()
{
BitArray ba = new BitArray(new bool[] {true,false,false,true,false,false,true,true,false,false,false,false});
List<int> positives = ba.GetBitPositions(true);
List<int> negatives = ba.GetBitPositions(false);
}
public static class BitArrayExtensions
{
public static List<int> GetBitPositions(this BitArray ba, bool MatchCondition)
{
List<int> pos = new List<int>();
for (int i = 0; i < ba.Length; i++)
{
if (ba[i] == MatchCondition)
pos.Add(i);
}
return pos;
}
}

Related

How create an adjacency matrix of a Maze graph

I'm working on making a maze Generator using Prim's Algorithm. I understand i have to make an undirected weighted graph and represent it on an Adjacency Matrix or List. i created the boolean[][] adjacenyMatrix array to show which edges currently exist in the maze. But i have an issue trying to implement the algorithm i thought of. Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter the size of the maze");
int mazeHeight = scanner.nextInt();
int mazeWidth = scanner.nextInt();
int noOfNodes = mazeHeight * mazeWidth;
boolean[][] adjacencyMatrix = new boolean[noOfNodes][noOfNodes];
for (int i = 0; i < mazeHeight; i++) {
for (int j = 0; j < mazeWidth; j++ ) {
// Edges exist from left to right
adjacencyMatrix[i][j] = true;
adjacencyMatrix[j][i] = true;
}
}
for (int i = 0; i < mazeWidth; i++) {
for (int j = 0; j < noOfNodes; j + mazeWidth) { // <-----------I'm having an issue here; Not a statement
// Edges exist from top to bottom
adjacencyMatrix[i][j] = true;
adjacencyMatrix[j][i] = true;
}
}
}
}
After taking a break; i looked over it and realised that i forgot to include the "=" symbol >.<
so j += mazeWidth

2D array traversal to get distinct 7 digit number combos

I ran into a tricky question from an interview prep book which goes..
You have a 3 by 3 matrix containing integers 1 to 9 as shown below
1 2 3
4 5 6
7 8 9
How do you get unique 7 digit number combos with the first numbers all starting with 4 (matrix[1][0]). The traversal is meant to be like that of a rook on a chess board.. 1 way either horizontally or vertically...(Having 4125874 is valid 7 digit combo btw).
I tried writing some code and doing regular 2D matrix traversal with a boolean visited flag here to get an answer and storing each combo in a hashSet to ensure uniqueness but I am stuck. Any kind comments, hints and code revisions to get me code working would be appreciated.
class Ideone
{
void dfs(int[][] matrix, boolean visited) //considered dfs with a boolean visited flag but I am stuck. I want to make my solution recursive
{
boolean visited = false;
}
public static HashSet<String> get7DigitCombo(int[][] matrix)
{
String result = "";
int[][] cache = matrix.clone();
Set<String> comboSet = new HashSet<String>();
boolean visited = false;
int resultStart = matrix[1][0];
for(int row = 1; row < matrix.length; row++)
{
for(int col = 0; col < matrix[0].length; col++)
{
if (visited == false & result.length < 7)
{
result += "" + (matrix[row + 1][col] || matrix[row -1][col] || matrix[row][col+1] || matrix[row][col-1]);
}
}
}
comboSet.add(result);
return comboSet;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[][] matrix = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
HashSet<String> comboSet = get7DigitCombo(matrix);
System.out.print(comboSet);
}
}
The following mcve demonstrates recursively getting neighbors and accumulating then into
unique combinations.
The code is documented with comments:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class Ideone
{
private static final int SIZE = 7; //size of combo
private static int[][] directions = { //represents moving directions
{-1, 0}, //up
{ 0,-1}, //left
{ 0, 1}, //right
{ 1, 0} //down
};
public static void main (String[] args) throws java.lang.Exception
{
int[][] matrix = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
Set<String> comboSet = get7DigitCombo(matrix);
System.out.print(comboSet.size());
}
public static Set<String> get7DigitCombo(int[][] matrix)
{
Set<String> comboSet = new HashSet<>();
get7DigitCombo(1, 0, matrix, String.valueOf(matrix[1][0]), comboSet);
return comboSet;
}
//recursively get all neighbors. generate combos by appending each neighbor
//combo represents a single combination. combos accumulates combination
static void get7DigitCombo(int row, int col, int[][] matrix, String combo, Set<String> combos){
if(combo !=null && combo.length() == SIZE) { //when combo reached the right size, add it
//System.out.println(combo);
combos.add(combo);
return;
}
//get and iterate over all adjacent neighbors
for(int[] neighbor : getNeighbors(row, col, matrix)){
get7DigitCombo(neighbor[0], neighbor[1], matrix, combo+neighbor[2], combos);
}
}
//return list of adjacent neighbors. each neighbor is represented by
//int[3]: row, column, value
private static List<int[]> getNeighbors(int row, int col, int[][] matrix) {
List<int[]> neighbors = new ArrayList<>();
for(int[] dir : directions){
int newRow = row + dir[0] ; int newCol = col + dir[1];
if(isValidAddress(newRow, newCol, matrix)) {
neighbors.add( new int[]{newRow,newCol, matrix[newRow][newCol]});
}
}
return neighbors;
}
private static boolean isValidAddress(int row, int col, int[][] matrix) {
if(row < 0 || col < 0) return false;
if(row >= matrix.length || col >= matrix[row].length) return false;
return true;
}
}
This is a pacman problem.
You must look for or define the neighbors of each matrix value.
Then cross the matrix fallowing the neighbors of each matrix value.
It usually resolves with recursive functions.
I think you code must be change from the ground using a different approach.

Making 2d Array Java

say I have a 1D array like
int[] array1d = {1,2,3}
I would like to convert it into 2D array2d[3][2] which holding 2 int that are different. E.g.:
1 2
1 3
2 3
currently I made this
int[] array1d = new int[3];
array1d[0] = 1;
array1d[1] = 2;
array1d[2] = 3;
int[][] array2d = new int[3][2];
for (int i=0; i<3; i++) {
for (int j=0; j<2; j++) {
array2d[i][j] = array1d[j];
}
}
but it gives me only 1,2.
Generally speaking, what you want is called combinations (in your example, of size 2 taken from a 3-sized array). So, order does not matter (e.g. [1, 2] equals [2, 1]).
As already specified in the comments, you should consider a more general solution and one can be found here. Besides the actual code, you will also find a code reviews from Codereview community.
i have done this using random numbers.try this code
` import java.util.Random;
public final class RandomInteger {
public static void main(String... aArgs){
Random randomGenerator = new Random();
int[] array1d = new int[3];
array1d[0] = 1;
array1d[1] = 2;
array1d[2] = 3;
int[] array2d = new int[3][2];
int randomInt;
for (int i=0; i<3; i++) {
for (int j=0; j<2; j++) {
randomInt = randomGenerator.nextInt(3);
array2d[i][j] = array1d[randomInt];
}
}
}
}
`

MPI min function in reduce

I am trying to find the minimum number in my array of integers, however, it returns 0.
import mpi.*;
import java.util.Random;
class AddIntSR
{
public static void main(String[] params) throws Exception
{
MPI.Init(params);
int me = MPI.COMM_WORLD.Rank();
int size = MPI.COMM_WORLD.Size();
final int CHUNKSIZE = 1;
final int ROOT = 0;
Random rg = new Random();
int [] bigBuf = new int[CHUNKSIZE *size];
int [] smallBuf = new int[CHUNKSIZE];
int [] minBuf = new int[1];
int localTotal = 0;
if (me == ROOT)
{
for(int i = 0; i< bigBuf.length; i++)
bigBuf[i] = rg.nextInt(10);
for(int i = 0; i< bigBuf.length; i++)
System.out.println("bigBuf "+bigBuf[i]);
}
MPI.COMM_WORLD.Scatter(bigBuf,0,CHUNKSIZE,MPI.INT,smallBuf,0,CHUNKSIZE,MPI.INT,ROOT);
if(me!= ROOT)
{
System.out.println("smallBuf "+me+ ": "+smallBuf[0]);
for(int i = 0; i < smallBuf.length; i++)
localTotal += smallBuf[i];
}
MPI.COMM_WORLD.Reduce(new int[]{localTotal},0,bigBuf,0,1,MPI.INT,MPI.MAX,ROOT);
MPI.COMM_WORLD.Reduce(new int[]{localTotal},0,minBuf,0,1,MPI.INT,MPI.MIN,ROOT);
if(me == ROOT)
{
System.out.println(bigBuf[0]);
System.out.println(minBuf[0]);
}
}
}
I am not sure why it does not work. The maximum function seems to work fine.
Also, how would I be able to access the integer that is sent to processor 0 so it is included in the min/max comparison?
Thank you.
The MIN reduction always results in 0 since localTotal is always 0 in rank ROOT and this is indeed the minimum value.
After the MPI.COMM_WORLD.Scatter call, all process including ROOT will have a piece of data in their smallBuf. Therefore you should remove the following conditional, i.e.:
if(me!= ROOT)
{
System.out.println("smallBuf "+me+ ": "+smallBuf[0]);
for(int i = 0; i < smallBuf.length; i++)
localTotal += smallBuf[i];
}
should become simply:
System.out.println("smallBuf "+me+ ": "+smallBuf[0]);
for(int i = 0; i < smallBuf.length; i++)
localTotal += smallBuf[i];

An interview question - implement Biginteger Multiply

Implement Biginteger Multiply
use integer array to store a biginteger
like 297897654 will be stored as {2,9,7,8,9,7,6,5,4}
implement the multiply function for bigintegers
Expamples: {2, 9, 8, 8, 9, 8} * {3,6,3,4,5,8,9,1,2} = {1,0,8,6,3,7,1,4,1,8,7,8,9,7,6}
I failed to implement this class and thought it for a few weeks, couldn't get the answer.
Anybody can help me implement it using C#/Java?
Thanks a lot.
Do you know how to do multiplication on paper?
123
x 456
-----
738
615
492
-----
56088
I would just implement that algorithm in code.
C++ Implementation:
Source Code:
#include <iostream>
using namespace std;
int main()
{
int a[10] = {8,9,8,8,9,2};
int b[10] = {2,1,9,8,5,4,3,6,3};
// INPUT DISPLAY
for(int i=9;i>=0;i--) cout << a[i];
cout << " x ";
for(int i=9;i>=0;i--) cout << b[i];
cout << " = ";
int c[20] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
for(int i=0;i<10;i++)
{
int carry = 0;
for(int j=0;j<10;j++)
{
int t = (a[j] * b[i]) + c[i+j] + carry;
carry = t/10;
c[i+j] = t%10;
}
}
// RESULT DISPLAY
for(int i=19;i>=0;i--) cout << c[i];
cout << endl;
}
Output:
0000298898 x 0363458912 = 00000108637141878976
There is a superb algorithm called Karatsuba algorithm..Here
Which uses divide and conquer startegy..Where you can multiply large numbers..
I have implemented my it in java..
Using some manipulation..
package aoa;
import java.io.*;
public class LargeMult {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
// TODO code application logic here
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter 1st number");
String a=br.readLine();
System.out.println("Enter 2nd number");
String b=br.readLine();
System.out.println("Result:"+multiply(a,b));
}
static String multiply(String t1,String t2)
{
if(t1.length()>1&&t2.length()>1)
{
int mid1=t1.length()/2;
int mid2=t2.length()/2;
String a=t1.substring(0, mid1);//Al
String b=t1.substring(mid1, t1.length());//Ar
String c=t2.substring(0, mid2);//Bl
String d=t2.substring(mid2, t2.length());//Br
String s1=multiply(a, c);
String s2=multiply(a, d);
String s3=multiply(b, c);
String s4=multiply(b, d);
long ans;
ans=Long.parseLong(s1)*(long)Math.pow(10,
b.length()+d.length())+Long.parseLong(s3)*(long)Math.pow(10,d.length())+
Long.parseLong(s2)*(long)Math.pow(10, b.length())+Long.parseLong(s4);
return ans+"";
}
else
{
return (Integer.parseInt(t1)*Integer.parseInt(t2))+"";
}
}
}
I hope this helps!!Enjoy..
Give the number you want to multiply in integer type array i.e. int[] one & int[] two.
public class VeryLongMultiplication {
public static void main(String args[]){
int[] one={9,9,9,9,9,9};
String[] temp=new String[100];
int c=0;
String[] temp1=new String[100];
int c1=0;
int[] two={9,9,9,9,9,9};
int car=0,mul=1; int rem=0; int sum=0;
String str="";
////////////////////////////////////////////
for(int i=one.length-1;i>=0;i--)
{
for(int j=two.length-1;j>=0;j--)
{
mul=one[i]*two[j]+car;
rem=mul%10;
car=mul/10;
if(j>0)
str=rem+str;
else
str=mul+str;
}
temp[c]=str;
c++;
str="";
car=0;
}
////////////////////////////////////////
for(int jk=0;jk<c;jk++)
{
for(int l=c-jk;l>0;l--)
str="0"+str;
str=str+temp[jk];
for(int l=0;l<=jk-1;l++)
str=str+"0";
System.out.println(str);
temp1[c1]=str;
c1++;
str="";
}
///////////////////////////////////
String ag="";int carry=0;
System.out.println("========================================================");
for(int jw=temp1[0].length()-1;jw>=0;jw--)
{
for(int iw=0;iw<c1;iw++)
{
int x=temp1[iw].charAt(jw)-'0';
sum+=x;
}
sum+=carry;
int n=sum;
sum=n%10;carry=n/10;
ag=sum+ag;
sum=0;
}
System.out.println(ag);
}
}
Output:
0000008999991
0000089999910
0000899999100
0008999991000
0089999910000
0899999100000
______________
0999998000001
If you do it the long-hand way, you'll have to implement an Add() method too to add up all the parts at the end. I started there just to get the ball rolling. Once you have the Add() down, the Multipy() method gets implemented along the same lines.
public static int[] Add(int[] a, int[] b) {
var maxLen = (a.Length > b.Length ? a.Length : b.Length);
var carryOver = 0;
var result = new List<int>();
for (int i = 0; i < maxLen; i++) {
var idx1 = a.Length - i - 1;
var idx2 = b.Length - i - 1;
var val1 = (idx1 < 0 ? 0 : a[idx1]);
var val2 = (idx2 < 0 ? 0 : b[idx2]);
var addResult = (val1 + val2) + carryOver;
var strAddResult = String.Format("{0:00}", addResult);
carryOver = Convert.ToInt32(strAddResult.Substring(0, 1));
var partialAddResult = Convert.ToInt32(strAddResult.Substring(1));
result.Insert(0, partialAddResult);
}
if (carryOver > 0) result.Insert(0, carryOver);
return result.ToArray();
}
Hint: use divide-and-conquer to split the int into halves, this can effectively reduce the time complexity from O(n^2) to O(n^(log3)). The gist is the reduction of multiplication operations.
I'm posting java code that I wrote. Hope, this will help
import org.junit.Test;
import static org.junit.Assert.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by ${YogenRai} on 11/27/2015.
*
* method multiply BigInteger stored as digits in integer array and returns results
*/
public class BigIntegerMultiply {
public static List<Integer> multiply(int[] num1,int[] num2){
BigInteger first=new BigInteger(toString(num1));
BigInteger result=new BigInteger("0");
for (int i = num2.length-1,k=1; i >=0; i--,k=k*10) {
result = (first.multiply(BigInteger.valueOf(num2[i]))).multiply(BigInteger.valueOf(k)).add(result);
}
return convertToArray(result);
}
private static List<Integer> convertToArray(BigInteger result) {
List<Integer> rs=new ArrayList<>();
while (result.intValue()!=0){
int digit=result.mod(BigInteger.TEN).intValue();
rs.add(digit);
result = result.divide(BigInteger.TEN);
}
Collections.reverse(rs);
return rs;
}
public static String toString(int[] array){
StringBuilder sb=new StringBuilder();
for (int element:array){
sb.append(element);
}
return sb.toString();
}
#Test
public void testArray(){
int[] num1={2, 9, 8, 8, 9, 8};
int[] num2 = {3,6,3,4,5,8,9,1,2};
System.out.println(multiply(num1, num2));
}
}

Resources