Create two dimensional boolean array from two other arrays - java

I have a two dimensional integer array and a two dimensional double array. If a value in the double array is less than the integer value at the same position of the two dimensional array, then in that part of the boolean array the value would is true. If it is greater, then the boolean would be false.
How would I go about on this?
This is what I tried so far:
public static boolean[][] CompareIntDouble(int[][] pizza, double[][] pasta) {
boolean x = true;
for (int hotdog=0; hotdog < pizza.length; hotdog++) {
for (int toast=0; toast < pizza[hotdog].length; toast++) {
pizza[hotdog][toast] = hotdog * 10 + toast;
if (pasta[1][1] > pizza[1][1]) {
x = true;
} else {
x = false;
}
if (pasta[1][2] > pizza[1][2]) {
x = true;
} else {
x = false
}
}
}
}
Picture of the code

public static void main(String... args) throws IOException {
int[][] t1 = new int[2][2];
t1[0][0] = 0;
t1[0][1] = 1;
t1[1][0] = 2;
t1[1][1] = 3;
double[][] t2 = new double[2][2];
t2[0][0] = 3;
t2[0][1] = 2;
t2[1][0] = 1;
t2[1][1] = 0;
boolean[][] f = new boolean[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (t1[i][j] > t2[i][j]) {
f[i][j] = true;
} else {
f[i][j] = false;
}
System.out.println(i+" "+j+" :"+f[i][j]);
}
}
}
even tho you should try it by yourself first here you have a working example

Assuming that 2d input arrays have the same size
public static boolean[][] foo( int[][] a,double[][]b) {
boolean[][] c = new boolean[a.length][a.length];
for (int i=0;i<a[0].length ;i++ ) {
for (int j=0;j<a.length ;j++ ) {
c[i][j]= (a[i][j]>(int)b[i][j]);
}
}
return c;
}

Related

Find all connected components and their sizes in a graph

I'm trying to find all connected components and their sizes in a graph. I don't know why, but the size is always 0. Maybe something is wrong in the method.
This is the problem that I am trying to solve. https://www.codechef.com/LRNDSA08/problems/FIRESC
public class B {
static void dfs(int s, int v, boolean[] visited, ArrayList<ArrayList<Integer>> adj) {
s++;
visited[v] = true;
for (int u : adj.get(v)) {
if (!visited[u]) {
dfs(s, u, visited, adj);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StringBuilder str = new StringBuilder();
int t = sc.nextInt();
for (int xx = 0; xx < t; xx++) {
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr.add(new ArrayList<Integer>());
}
boolean[] visited = new boolean[n];
Arrays.fill(visited, false);
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
a--;
b--;
arr.get(a).add(b);
arr.get(b).add(a);
}
long ways = 1;
int groups = 0;
for (int i = 0; i < n; i++) {
if (visited[i])
continue;
int size = 0;
dfs(size, i, visited, arr);
groups++;
ways *= size;
ways %= 1000000007;
}
System.out.println(groups + " " + ways);
}
}
}
You know size is passed as value and not as reference. So it won't get updated after you return from the call. One thing you could do is define a single element array like
int[] size = new int[1];
and modify your dfs like:
static void dfs(int[] s, int v, boolean[] visited, ArrayList<ArrayList<Integer>> adj) {
s[0]++;
visited[v] = true;
for (int u : adj.get(v)) {
if (!visited[u]) {
dfs(s, u, visited, adj);
}
}
}
Then your result will be in size[0] which you can use to update ways like ways *= size[0]
Or you could modify dfs to return size which is a cleaner way to get the size like below:
static int dfs(int v, boolean[] visited, ArrayList<ArrayList<Integer>> adj) {
visited[v] = true;
int sz = 1;
for (int u : adj.get(v)) {
if (!visited[u]) {
sz += dfs(u, visited, adj);
}
}
return sz;
}
And it seems like you have a misconception on how variables in Java work (see). Incrementing an int variable that resides on one lair of the stack would not affect a variable on another stack lair. That's why the size is always 0.
The following solution passes base test on CodeChef:
public class CountComponents {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
for (int i = 0; i < testCases; i++) {
EmployeeGraph graph = parseGraph(sc);
graph.countComponentsAndComponentSizes();
}
}
public static EmployeeGraph parseGraph(Scanner sc) {
int employeeCount = sc.nextInt();
int connectionsCount = sc.nextInt();
boolean[][] adjacencyMatrix = new boolean[employeeCount][employeeCount];
for (int i = 0; i < connectionsCount; i++) {
int row = sc.nextInt() - 1;
int col = sc.nextInt() - 1;
adjacencyMatrix[row][col] = true;
adjacencyMatrix[col][row] = true;
}
return new EmployeeGraph(adjacencyMatrix);
}
}
class EmployeeGraph {
public static final int BILLION_SEVEN = 1_000_000_007;
private boolean[][] adjacencyMatrix;
public EmployeeGraph(boolean[][] adjacencyMatrix) {
this.adjacencyMatrix = adjacencyMatrix;
}
public void countComponentsAndComponentSizes() {
boolean[] visited = new boolean[adjacencyMatrix.length];
int componentCount = 0;
int waysToChooseCaptain = 1;
for (int row = 0; row < adjacencyMatrix.length; row++) {
if (!visited[row]) {
componentCount++;
waysToChooseCaptain = (waysToChooseCaptain % BILLION_SEVEN) * dfs(visited, row);
}
}
System.out.println(componentCount + " " + waysToChooseCaptain % BILLION_SEVEN);
}
public int dfs(boolean[] visited, int row) {
visited[row] = true; // marking the current employee as visited
int size = 1; // this component consists at least from 1 employee
for (int col = 0; col < adjacencyMatrix.length; col++) {
if (adjacencyMatrix[row][col] && !visited[col]) {
size += dfs(visited, col);
}
}
return size;
}
}

How to lessen memory usage when using many ArraysLists in Java

I'm making a program to play Misere Nim, and I'm running into some problems with memory. I use ArrayLists to hold the possible moves that could be done, and this is causing an OutOfMemory exception. How can I lessen the memory I use when using ArrayLists? Should I be clearing something after every run?
EDIT: added copy method
EDIT: full project can be found at https://github.com/DatOneRam/ScienceFair
do
{
int tempWin = board.playRound();
if (tempWin == 0)
stratWins++;
else
randWins++;
}
while (rounds <= 10000);
public int playRound()
{
Board board = new Board();
NimBot strat = new NimBot(board);
NimBot rand = new NimBot(board);
do
{
strat.makeStrategicMove();
if (board.hasEnded())
break;
rand.makeRandomMove();
}
while (!board.hasEnded());
return board.getPlayer();
}
public void makeStrategicMove()
{
ArrayList<int[]> goodMoves = board.getGoodMoves();
Random rand = new Random();
int[] move;
if (goodMoves.size() != 0)
{
move = goodMoves.get(rand.nextInt(goodMoves.size()));
}
else
{
ArrayList<int[]> simpleMoves = board.getSimpleMoves();
move = simpleMoves.get(rand.nextInt(simpleMoves.size()));
}
board.setPosition(move);
}
public void makeRandomMove()
{
ArrayList<int[]> moves = board.getMoves();
Random rand = new Random();
int[] move = moves.get(rand.nextInt(moves.size()));
board.setPosition(move);
}
public ArrayList<int[]> getMoves()
{
ArrayList<int[]> x = new ArrayList<int[]>();
int j = 0, i = 1;
x.add(0, copy(position));
do
{
x.add(i, copy(position));
if (x.get(i-1)[j] == 0)
j++;
x.get(i)[j] = x.get(i-1)[j] - 1;
i++;
if (x.get(i-1)[j] == 0)
{
j++;
if (j == 5)
{
break;
}
}
}
while(x.get(i - 1)[j] != 0);
for (int r = 0; r < x.size(); r++)
{
x.get(r)[4] = toggle(x.get(r)[4]);
}
x.remove(0);
//resize(x);
return x;
}
public ArrayList<int[]> getSimpleMoves()
{
ArrayList<int[]> x = new ArrayList<int[]>(4);
for (int i = 0; i < 4; i++)
{
x.add(copy(position));
x.get(i)[i] = position[i] - 1;
x.get(i)[4] = toggle(x.get(i)[4]);
if (x.get(i)[i] < 0)
x.get(i)[i] = 0;
}
//resize(x);
return x;
}
public int[] copy(int[] y)
{
int[] z = new int[y.length];
for (int i = 0; i < y.length; i++)
z[i] = y[i];
return z;
}
I apologize if I put too much code here, I wasn't sure how to shorten it.

Array Index out of bounds Java program

Can someone please explain to me why I'm getting an array out of bounds error?
longestStreak : array of booleans -> integer
Purpose: computes the length of a longest streak of consecutive true occurrences in the input argument values
Input : values is a non-null array of booleans with length at least 1
output : outputs the maximal number of consecutive trues found in the input array
import java.util.Arrays;
public class Problem3 {
public static void main (String[] args) {
boolean[] test = new boolean[] {true, false, true, true, false};
int[] o = longestStreak(test);
System.out.println(o);
}
public static int[] longestStreak(boolean[] values) {
int streak = 0;
int max = 0;
int arrsize = 0;
for (int i = 0; i < values.length; i++) {
if (values[i]) {
streak++;
max = streak;
arrsize++;
}
else {
streak = 0;
}
}
int[] output = new int[arrsize];
for (int i = 0; i < values.length; i++) {
for (int z = 1; z < values.length; z++) {
if (values[i]) {
i = output[z];
}
}
}
return output;
}
}
I am guessing it's the following:
When values[i] is true the line : i = output [z]; will try to reach an index which might be greater than 2.
I think the problematic line of code is
i = output[z];
The reason is because I think that you could be setting i equal to a value that is greater than values.length
Ok, so I reread your problem statement. This code below will fix it for you and it works. just plug it in:
import java.util.Arrays;
public class Test {
public static void main (String []args) {
boolean[] test = new boolean[] {true, false, true, true, false};
int[] o = longestStreak(test);
System.out.println ("{"+o[0] + ", " + o[1]+"}");
}
public static int[] longestStreak(boolean[] values) {
int streak = 0;
int max =0;
int arrsize =0;
int maxStart = 0;
int[] r = new int[2];
for (int i=0; i<values.length; i++) {
if (values[i]) {
streak++;
// max =streak;
// arrsize++;
}
else {
if (streak > max) {
max = streak;
maxStart = 0;
maxStart = i - streak;
}
streak = 0;
}
}
r[0] = max;
r[1] = maxStart;
return r;
}
}
Should use something like this, instead:
public static int longestStreak(boolean... values)
{
int streak = 0;
int max =0;
for (int i = 0; i < values.length; ++i)
{
if (values[i])
streak++;
else
{
if (streak > max)
max = streak;
streak = 0;
}
}
return max;
}
This problem is occurred because the values.length is greater than arrsize. Consider following scenario.
In your input, there are 3 true values and 2 false values. Your code says that arraysize will be increment if values[i] is true. So here arraysize is 3, but values.length is the size of boolean array which contains true and false also which is 5. Your inner loop is running up to values.length i.e. 5 and your output array's size is 3. That's why ArrayIndexOutOfBoundsException exception occurred.
for (int i = 0; i < values.length; i++) {
for (int z = 1; z < values.length; z++) {
if (values[i]) {
i = output[z];
}
}
}
Here output array size will be less than values array size. Hence it throws ArrayIndexOutOfBoundsExecption.
Here is a modified code that works, using ArrayList.
public static void main(String[] args) {
boolean[] test = new boolean[] { true, false, true, true, false };
ArrayList<Integer> o = longestStreak(test);
for(int x : o) System.out.println(x);
}
public static ArrayList<Integer> longestStreak(boolean[] values) {
ArrayList<Integer> maxStreak = new ArrayList<Integer>();
int currentStreak = 0;
for (int x = 0; x < values.length; x++)
if(values[x]) {
if (++currentStreak == 1)maxStreak.clear();
if (currentStreak >= maxStreak.size()) maxStreak.add(x);
} else currentStreak = 0;
return maxStreak;
}
Here is the output (positions of the max streak in boolean array)
2
3

Java Array Index out of Bounds Error

I'm working on a brute force approach to the traveling salesman problem. I have a certain line that produces the ArrayIndexOutOfBounds exception, however all the arrays used there have more than enough space. The particular line of code:
testCity[0][a] = cities[0][(int) cityList[a]];
This is where I initialize testCity:
int[][] testCity = new int[2][CITIES+10];
cities:
public static int[][] cities = new int[2][CITIES+10];
And, finally, cityList:
Object[] cityList = new Integer[CITIES+10];
This is the entire error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at BruteF.permute(BruteF.java:39)
at BruteF.permute(BruteF.java:30)
at BruteF.permute(BruteF.java:30)
at BruteF.permute(BruteF.java:30)
at BruteF.main(BruteF.java:11)
And here is the code:
public class BruteF {
public static final int CITIES = 5;
public static int[][] cities = new int[2][CITIES+10];
public static int[][] bestCity = new int[2][CITIES+10];
public static double bestDistance = 1000;
public static int[][] testCity = new int[2][CITIES+10];
public static Object[] cityList = new Integer[CITIES+10];
public static void main(String[] args)
{
permute(java.util.Arrays.asList(1,2,3,4), 0);
for (int i = 0;i < CITIES;i++)
{
System.out.println(bestCity[0][i] + "," + bestCity[1][i]);
}
}
static void permute(java.util.List<Integer> arr, int k){
cities[0][0] = 1;
cities[1][0] = 1;
cities[0][1] = 2;
cities[1][1] = 5;
cities[0][2] = 3;
cities[1][2] = 2;
cities[0][3] = 4;
cities[1][3] = 3;
int originalX = cities[0][0];
int originalY = cities[1][0];
for(int i = k; i < arr.size(); i++){
java.util.Collections.swap(arr, i, k);
permute(arr, k+1);
java.util.Collections.swap(arr, k, i);
}
if (k == arr.size() -1){
for (int i = 0;i < CITIES;i++)
{
cityList = arr.toArray();
for (int a = 0;a < CITIES;a++)
{
testCity[0][a] = cities[0][(int) cityList[a]];
}
if (distance(testCity,CITIES,originalX, originalY) < bestDistance)
{
bestCity = testCity;
bestDistance = distance(testCity,CITIES, originalX, originalY);
}
}
}
}
static double distance (int[][] cities, int CITIES, int originalX, int originalY)
{
int[][] taken = new int[2][CITIES+1];
int takenCounter = 0;
double distance = 0;
cities[0][CITIES] = cities[0][0];
cities[1][CITIES] = cities[1][0];
for (int i = 0;i <= CITIES;i++)
{
for (int z = 0;z <= CITIES;z++)
{
if (cities[0][i] == taken[0][z] && cities[1][i] == taken[1][z])
{
return CITIES*1000; //possible error here
}
else {
taken[0][takenCounter] = cities[0][i];
taken[1][takenCounter] = cities[1][i];
}
}
if (cities[0][0] != originalX && cities[1][0] != originalY)
{
return CITIES*1000; //POSSIBLE BUG HERE
}
distance = distance + Math.sqrt(Math.pow(cities[0][i+1]-cities[0][i],2) + Math.pow(cities[1][i+1]-cities[1][i],2));
}
return distance;
}
}
Why is this happenening? What can I do to fix it?
It is giving out of bound exception : 4
when you are initializing cityList i.e. cityList = arr.toArray(); your array cityList[] = {1,2,3,4} , i.e of size 4 from 0 to 3.
And you are running a for loop i.e
for (int a = 0;a < CITIES;a++)
from a=0 to CITIES , so as the moment arrive when a=4, it gives out of bound error.

Shifting an array after removing a value (Java)

I made a program that makes an array of random ints and doubles in size if the user tries to add an int. Example: 1|2|3|4 if they were to add another int it would look like 1|2|3|4|5|0|0|0. I have made a method to add an int which works but now I am trying to make methods that remove one of a certain int and another that removes all of a certain int. for example removeInt(3) would give me 1|2|0|4|5|0|0|0. I have the first part working so that it shifts the zero to the end like this 1|2|4|5|0|0|0|0 but cannot get it to work for more than one of the same value. Any suggestions?
// ****************************************************************
// IntegerList.java
//
// Define an IntegerList class with methods to create & fill
// a list of integers.
//
// ****************************************************************
public class IntegerList
{
int[] list; //values in the list
//-------------------------------------------------------
//create a list of the given size
//-------------------------------------------------------
public IntegerList(int size)
{
list = new int[size];
}
//-------------------------------------------------------
//fill array with integers between 1 and 100, inclusive
//-------------------------------------------------------
public void randomize()
{
for (int i=0; i<list.length; i++)
list[i] = (int)(Math.random() * 100) + 1;
}
//-------------------------------------------==----------
//print array elements with indices
//-------------------------------------------------------
public void print()
{
for (int i=0; i<list.length; i++)
System.out.println(i + ":\t" + list[i]);
}
public void addElement(int newVal){
boolean full = true;
System.out.println(list.length);
int position = 0;
int place;
while(position < list.length){
System.out.println("HERE");
if(list[position]==0){
System.out.println("here");
full = false;
place = position;
System.out.println(place);
}
position = position+1;
}
if(full == true){
list = increaseSize(list);
System.out.println("L"+list.length);
full = false;
}
for(int i = 0;i<list.length;i++){
if(list[i]==0){
if(i<position){
position = i;
System.out.println(list.length);
}
}
}
list[position] = newVal;
}
public void removeFirst(int newVal){
int position = 0;
boolean removed = false;
for(int i = 0; i<list.length;i++){
if(list[i] == newVal){
list[i]=0;
position = i;
removed = true;
break;
}
}
if(removed==true){
for(int i = position;i<list.length;i++){
if(i!=list.length-1){
list[i]=list[i+1];
}
}
list[list.length-1]= 0;
}
}
public void removeAll(int newVal){
int position = 0;
boolean removed = false;
for(int i = 0; i<list.length;i++){
if(list[i] == newVal){
list[i]=0;
position = i;
removed = true;
}
}
if(removed==true){
for(int i = 0;i<list.length;i++){
if(i!=list.length-1 && list[i+1]==newVal){
list[i]=0;
}
if(list[i]==newVal){
list[i]=0;
}
}
}
}
public static int[] increaseSize(int[] x){
int newLength = x.length *2;
int[] newx = new int[newLength];
for(int i = 0; i<x.length; i++){
newx[i] = x[i];
}
return newx;
}
public static int[] halfSize(int[] x){
int[] newx = new int[x.length / 2];
for(int i = 0; i<x.length; i++){
newx[i] = x[i];
}
return newx;
}
}
I believe there's an easier way to implement your removeAll method. Move 2 (rather than 1) indices through your array constantly shifting the values over the items you are removing;
int dest = 0;
int source = 0;
while (source < array.length) {
if (array[dest] != valueToRemove)
dest++;
array[dest] = array[source++];
}
while (dest < array.length) {
array[dest++] = 0;
}
I executed your code and found out that the problem is in this piece, under removeAll()...
if(removed){
for(int i = 0;i<list.length;i++){
if(i!=list.length-1 && list[i+1]==newVal){
list[i]=0;
}
if(list[i]==newVal){
list[i]=0;
}
}
}
If you comment out and try once, you will see the removeAll() is working and your desired number is replaced with 0s. Now why you don't simply check your numbers and shift(sorting), if they are greater than 0 to the left?

Categories