I am trying to solve this exercise but I am facing some problems while trying to do so. In logical terms, I think that I am thinking right. Could you take a look at my code please and try to help me?
import java.util.Arrays;
import java.util.Random;
public class exercicio_4_alapata {
public static void main(String[] args) {
int [] Array_numal;
Array_numal = new int [100];
int [] ArrayOrdenado;
ArrayOrdenado = new int [100];
int posicao_array;
int posicao_array2 = 0;
for (posicao_array = 0; posicao_array < Array_numal.length; posicao_array ++) {
Random rand = new Random();
Array_numal [posicao_array] = rand.nextInt(101);
}
int maior = Array_numal [0];
while (maior != ArrayOrdenado[99]) {
for (posicao_array2 = 0; posicao_array2 == 99; posicao_array2 ++) {
for (posicao_array = 0; posicao_array < Array_numal.length; posicao_array ++) {
if ((Array_numal[posicao_array] > maior) && (maior < ArrayOrdenado [posicao_array2 - 1])) {
maior = ArrayOrdenado [posicao_array2];
}
}
}
}
for (posicao_array2 = 0; posicao_array2 < ArrayOrdenado.length; posicao_array2 ++) {
System.out.println(ArrayOrdenado[posicao_array2]);
}
}
}
You could try to use Arrays.sort(T[] a, Comparator c)):
Arrays.sort(a, Collections.reverseOrder());
Related
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;
}
}
I have a homework assignment where a user must input the size of an array and then the array must be filled with random values. I am having issues filling the array with something that isn't garbage values. I am sure there are other issues with my code as well but this is the biggest issue I'm currently trying to solve. Any help would be appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
public class rotateArray1
{
public static int randomFill()
{
Random rand = new Random();
int randomInt = rand.nextInt();
return randomInt;
}
void leftRotate(int arr[], int d, int n)
{
int i;
for(i=0; i < d; i++)
leftRotateByOne(arr, n);
}
void leftRotateByOne(int arr[], int n)
{
int i,temp;
temp = arr[0];
for(i=0; i < n -1; i++)
arr[i] = arr[i+1];
arr[i] = temp;
}
void printArray(int arr[],int size)
{
int i;
for (i = 0; i<size;i++)
System.out.print(arr[i]+ "");
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter size of array");
int x= input.nextInt();
int[] arr = new int[x];
for(int i = 0; i<x; i++){
arr[i] = randomFill();
}
rotateArray rotate = new rotateArray();
rotate.leftRotate(arr, 2, x);
rotate.printArray(arr, x);
System.exit(0);
}
}
Just pass a reference to the array to randomFill and do it in one shot. That helps the code in main() read easier and uses one instance of a Random which is probably more what you want as was pointed out.
import java.util.Random;
public class JavaTest {
public static void main(String... args) {
int[] array = new int[10];
randomFill(array);
for(int i = 0; i < array.length ; i++){
System.out.println("array["+i+"] = "+array[i]);
}
}
static void randomFill(int[] array)
{
Random rand = new Random();
for(int i = 0; i < array.length ; i++){
array[i] = rand.nextInt();
}
}
}
Output:
array[0] = 431970257
array[1] = 9846759
array[2] = 1919609165
array[3] = -544686432
array[4] = 655372436
array[5] = -331654257
array[6] = -1187729012
array[7] = 1378209257
array[8] = -1225327561
array[9] = 1887304192
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.
public class AssignmentChapter8
{
public static void main(String[] args)
{
int randomNumbers = new int[100];
int counter = 0;
while(counter < randomNumbers.length)
{
randomNumbers[counter] = (int)(Math.random() * 25);
counter++;
}
int oddNumbers[] = new int[100];
oddNumbers[] = getOddNumbers(randomNumbers);
int evenNumbers[] = new int[100];
evenNumbers[] = getEvenNumbers(randomNumbers);
System.out.println("The odd numbers are:");
for(int k = 0; k < oddNumbers.length; k++)
System.out.print("\t" + oddNumbers[k]);
System.out.println("The even numbers are:");
for(int l = 0; l < evenNumbers.length; l++)
System.out.print("\t" + evenNumbers[l]);
}
public static int getOddNumbers(int randomNumbers)
{
int oddNumbers[] = new int[100];
int counterA = 0;
int counterB = 0;
int counter = 0;
int placeholder;
while(counter < randomNumbers.length)
{
if(randomNumbers[counterA] % 2 > 0)
{
oddNumbers[counterB] = randomNumbers[counterA];
counterB++;
}
counterA++;
counter++;
}
return oddNumbers;
}
public static int getEvenNumbers(int randomNumbers)
{
int evenNumbers[] = new int[100];
int counterA = 0;
int counterB = 0;
int counter = 0;
int placeholder;
while(counter < randomNumbers.length)
{
if(randomNumbers[counterA] % 2 > 0)
{
evenNumbers[counterB] = randomNumbers[counterA];
counterB++;
}
counterA++;
counter++;
}
return evenNumbers;
}
}
I have been trying to execute a program to sort variables in arrays, but I keep getting a ';' expected error in the line after declaration of the array where the program is supposed to retrieve an array from a function. Any help would be appreciated.
This is bad syntax (which causes the ';' expected error ):
oddNumbers[] = getOddNumbers(randomNumbers);
The brackets are not needed. You can do this:
oddNumbers = getOddNumbers(randomNumbers);
Besides that, you have plenty of errors:
int randomNumbers[] = new int[100]; // you need the brackets
Your return value in the method declaration is wrong (you are returning an array, not an int):
public static int[] getEvenNumbers(int randomNumbers)
int oddNumbers[] = new int[100];
By initializing oddNumbers become an array. when you want to assign values,
oddNumbers={elements of array}
Both left and right hand side both should arrays.
May be you should use IDE for coding then it may help you to understand some issues like this.
I am making a maze game with enumerated types to hold the values of walls, open spaces (etc) and i am not sure why this code does not work, i am trying to create a new board and set everything to open, then go through and randomly set values to the spots in the array.
maze = new Cell[row][col];
for (int r = 0; r < maze.length; r++) {
for (int c = 0; c < maze.length; c++)
maze[r][c].setType(CellType.OPEN);
}
Random randomMaze = new Random();
for (int ran = 0; ran <= numWalls ; ran++){
maze[randomMaze.nextInt(maze.length)][randomMaze.nextInt(maze.length)].setType(CellType.WALL);
}
this will do what you said. not sure you will get the kind of maze you want:
import java.util.Random;
class Maze {
enum CellType {
open,wall;
}
Maze(int n) {
this.n=n;
maze=new CellType[n][n];
init();
}
private void init() {
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
maze[i][j]=CellType.open;
}
void randomize(int walls) {
init();
Random random=new Random();
for(int i=0;i<=walls;i++)
maze[random.nextInt(n)][random.nextInt(n)]=CellType.wall;
}
public String toString() {
StringBuffer sb=new StringBuffer();
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++)
switch(maze[i][j]) {
case open:
sb.append(' ');
break;
case wall:
sb.append('|');
break;
}
sb.append('\n');
}
return sb.toString();
}
final int n;
CellType[][] maze;
}
public class Main {
public static void main(String[] args) {
Maze maze=new Maze(5);
System.out.println(maze);
maze.randomize(4);
System.out.println(maze);
}
}
I think, your inner loop should be something like
for (int c = 0; c < maze[r].length; c++)
... with the [r].
I have not tried it though.
I think that your maze would be a good candidate for a class. Something like this should work:
import java.util.Random;
public class Maze {
private int[][] mMaze;
private int mRows;
private int mCols;
//enums here:
public static int CELL_TYPE_OPEN = 0;
public static int CELL_TYPE_WALL = 1;
public Maze(int rows, int cols){
mRows = rows;
mCols = cols;
mMaze = new int[mRows][mCols];
for (int r = 0; r < mRows; r++) {
for (int c = 0; c < mCols; c++) {
mMaze[r][c] = Maze.CELL_TYPE_OPEN;
}
}
}
public void RandomizeMaze(int numWalls){
Random randomMaze = new Random();
for (int ran = 0; ran <= numWalls ; ran++){
mMaze[randomMaze.nextInt(mRows)][randomMaze.nextInt(mCols)]=(Maze.CELL_TYPE_WALL);
}
}
}