MPI min function in reduce - mpi

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

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

Beginner coder checking if input is part of a cycle?

public Graph (int nb){
this.nbNodes = nb;
this.adjacency = new boolean [nb][nb];
for (int i = 0; i < nb; i++){
for (int j = 0; j < nb; j++){
this.adjacency[i][j] = false;
}
}
}
public void addEdge (int i, int j){
if(!(i<0 || i>=this.nbNodes|| j<0 || j>=this.nbNodes))
{
this.adjacency[i][j] = true;
this.adjacency[j][i] = true;
}
}
public void removeEdge (int i, int j){
if(!(i<0 || i>=this.nbNodes|| j<0 || j>=this.nbNodes))
{
this.adjacency[i][j] = false;
this.adjacency[j][i] = false;
}
}
public int nbEdges(){
int c =0;
for(int i=0; i<this.nbNodes; i++)
{
for(int j= 0; j<this.nbNodes; j++)
{
if(this.adjacency[i][j]==true)
{
c++;
}
}
}
return c/2;
}
public boolean cycle(int start){
return false;
}
A Graph has a number of nodes nbNodes and is characterized by its adjacency matrix adjacency. adjacency[i][j] states whether or not there is an edge from the i-th node to the j-th node.
the graphs are undirected.
I am a beginner coder and am having trouble writing cycle(int start)
It takes as input an integer, g.cycle(i) returns true if the i-th node is part of a cycle (and false otherwise).
does anyone have any idea on how I should approach this?

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

Unhandled exception error with two dimensional array

This dynamic programming algorithm is returning unhandled exception error probably due to the two dimensional arrays that I am using for various (and very large) number of inputs. I can't seem to figure out the issue here. The complete program as follows:
// A Dynamic Programming based solution for 0-1 Knapsack problem
#include<stdio.h>
#include<stdlib.h>
#define MAX 10000
int size;
int Weight;
int p[MAX];
int w[MAX];
// A utility function that returns maximum of two integers
int maximum(int a, int b) { return (a > b) ? a : b; }
// Returns the maximum value that can be put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int retVal;
int **K;
K = (int**)calloc(n+1, sizeof(int*));
for (i = 0; i < n + 1; ++i)
{
K[i] = (int*)calloc(W + 1, sizeof(int));
}
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i == 0 || w == 0)
K[i][w] = 0;
else if (wt[i - 1] <= w)
K[i][w] = maximum(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
else
K[i][w] = K[i - 1][w];
}
}
retVal = K[n][W];
for (i = 0; i < size + 1; i++)
free(K[i]);
free(K);
return retVal;
}
int random_in_range(unsigned int min, unsigned int max)
{
int base_random = rand();
if (RAND_MAX == base_random) return random_in_range(min, max);
int range = max - min,
remainder = RAND_MAX % range,
bucket = RAND_MAX / range;
if (base_random < RAND_MAX - remainder) {
return min + base_random / bucket;
}
else {
return random_in_range(min, max);
}
}
int main()
{
srand(time(NULL));
int val = 0;
int i, j;
//each input set is contained in an array
int batch[] = { 10, 20, 30, 40, 50, 5000, 10000 };
int sizeOfBatch = sizeof(batch) / sizeof(batch[0]);
//algorithms are called per size of the input array
for (i = 0; i < sizeOfBatch; i++){
printf("\n");
//dynamic array allocation (variable length to avoid stack overflow
//calloc is used to avoid garbage values
int *p = (int*)calloc(batch[i], sizeof(int));
int *w = (int*)calloc(batch[i], sizeof(int));
for (j = 0; j < batch[i]; j++){
p[j] = random_in_range(1, 500);
w[j] = random_in_range(1, 100);
}
size = batch[i];
Weight = batch[i] * 25;
printf("| %d ", batch[i]);
printf(" %d", knapSack(Weight, w, p, size));
free(p);
free(w);
}
_getch();
return 0;
}
Change this:
for (i = 0; i < size + 1; i++)
free(K[i]);
free(K);
return K[size][Weight];
To this:
int retVal;
...
retVal = K[size][Weight];
for (i = 0; i < size + 1; i++)
free(K[i]);
free(K);
return retVal;

When using scanf/cin, program works fine in debug mode but gives runtime error

I'm trying to take to the following input:
1
4
47 2 4 43577
The part of my code that deals with this is:
for (scanf("%d", &t); t --; )
{
int count = 0;
scanf("%d",&n);
for (int i = 0, x; i < n; ++ i)
{
scanf("%d",&x);
str = to_string(x);
f4[i] = get_count(str,'4');
f7[i] = get_count(str,'7');
}
However, with this I get a runtime error, which shows an access violation in the file free.c.
But, when I try to debug it, it runs well in the debug mode and gives the correct answer.
Also, when I output the variable x right after I input it, the program works well in runtime as well. This is shown in the following code, which runs fine in runtime as well:
for (scanf("%d", &t); t --; )
{
int count = 0;
scanf("%d",&n);
for (int i = 0, x; i < n; ++ i)
{
scanf("%d",&x);
cout<<"A"<<i<<" is "<<x<<'\n';
str = to_string(x);
f4[i] = get_count(str,'4');
f7[i] = get_count(str,'7');
}
Any idea why this may be happening?
Some of the stackoverflow users are saying that the code runs fine. I'm using VS 2012. Can this be something that is compiler specific?
The complete code:
#include<iostream>
#include<conio.h>
#include<string>
#include<math.h>
using namespace std;
int get_count(string s, char x)
{
int count = 0;
int l = s.length();
for(int i = 0; i < l;i++)
{
if (s[i] == x)
count++;
}
return count;
}
void main()
{
int * f4 = new int;
int * f7 = new int;
string * back = new string;
int n = 0;
int t = 0;
string str;
for (scanf("%d", &t); t --; )
{
int count = 0;
scanf("%d",&n);
for (int i = 0, x; i < n; ++ i)
{
scanf("%d",&x);
str = to_string(x);
f4[i] = get_count(str,'4');
f7[i] = get_count(str,'7');
}
for(int i = 0;i < n;i++)
{
for(int j = i; j < n;j++)
{
int c4 = 0;
int c7 = 0;
for(int k = i; k <= j;k++)
{
c4 += f4[k];
c7 += f7[k];
}
double value = pow((double)c4,(double)c7);
if(value <= (double)(j - i + 1)&&(c4!=2)&&(c7!=2))
{
count++;
//cout<<"yes"<<'\t';
}
}
}
cout<<"Ans: "<<count<<'\n';
}
//getch();
}
There are no other variable assignments apart from those in this code.
The exact error that I get with runtime is:
Unhandled exception at 0x7794E3BE (ntdll.dll) in Practice1.exe: 0xC0000005: Access violation reading location 0x38389246.
You did not include the "get_count" function. I think it has something to do with that function. I rewrote that function to return some number and I don't get that error. Try to assert that you are not attempting to use a null pointer in that function.
Works fine on my machine:
Here's what I changed
for (int i = 0, x; i < n; ++ i)
{
scanf("%d",&x);
stringstream ss;
ss << x;
str = ss.str();
f4[i] = get_count(str,'4');
f7[i] = get_count(str,'7');
}
Output:
1
4
47 2 4 43577
Ans: 5

Resources