Brute Force Algorithm Issue - java

I've look over the code several time but I keep getting a Array Out of Bound at the line that states:
sum = sum + vectorArray[z]; }
Can anyone see what's wrong?
public class HW1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// The numbers for n are not relevant
System.out.println("Please enter a number for the length of n.");
int n = input.nextInt();
// Creates an array with n values
int[] vectorArray = new int[n];
// Inputs random numbers into the array ranging from -100 to 100.
int dummy;
int temp = 0;
// Loop to generate negative and positive numbers into the array
for (int i = 0; i < n; i++) {
dummy = (int)(Math.random()*2);
if (dummy == 0) {
temp = -1;
} else {
temp = 1; }
vectorArray[i] = ((int)(Math.random()*101)) * temp;
System.out.println(vectorArray[i]); }
int max = -1;
int sum;
for (int x = 0; x < vectorArray.length; x++) {
for (int y = x; x < vectorArray.length; y++) {
sum = 0;
for (int z = x; z <= y; z++) {
sum = sum + vectorArray[z]; }
max = Math.max(max, sum);
} }
System.out.println("The max: " + max);
}
}

change x to y in the for loop
for (int y = x; y < vectorArray.length; y++) {
^
sum = 0;
for (int z = x; z <= y; z++) {
sum = sum + vectorArray[z]; }

Related

Can I, within the same file, use a previously printed line as an input to a new section?

public class Bonus1{
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] numbers = new int[n];
for (int i = 0; i < n; i++ ) {
numbers[i] = i;
}
for (int i = 0; i < n; i++ ) {
int r = i + (int)(Math.random() * (n - i));
int tmp = numbers[i];
numbers[i] = numbers[r];
numbers[r] = tmp;
System.out.print(numbers[i]);
}
int min = Integer.MAX_VALUE;
int count = 0;
while(data.hasNext()){
int y = data.nextInt();
if(y < min){
min = y;
count += 1;
}
}
System.out.println(count);
}
}
this code isn't complete, the first 2 for-loops will generate an array between 0 to a given number in the commandline -1
So for example java Bonus1 10 would first generate an array between 0-9 and then it will shuffle these numbers around so that it creates a random permutation.
the while loop is something I've used before to read input and determine how many times a new lowest number is detected. so for example if I get the permutation 7 8 2 3 4 5 1 0 6 9 it will count 7 as the lowest, then 2 as the lowest and then 1 as the lowest and finally 0 as the lowest, making the total amount of times a new lowest number has been detected 4.
but this only works if I use inputs, I need to use the previously generated output as the input in the same file, is there a clever way to do that?
You should iterate for the array numbers like this.
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = i;
}
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = numbers[i];
numbers[i] = numbers[r];
numbers[r] = tmp;
System.out.print(numbers[i]);
}
System.out.println();
int min = Integer.MAX_VALUE;
int count = 0;
for (int i = 0; i < n; ++i) {
int y = numbers[i];
if (y < min) {
min = y;
++count;
}
}
System.out.println(count);
}
output:
6457098123
3

Stuck on Discrete distribution having an issue with finishing the problem

Here is what I am suppose to be getting.
This is what I am actually getting.
Write a program DiscreteDistribution.java that takes an integer command-line argument m, followed by a sequence of positive integer command-line arguments a1,a2,…,an, and prints m random indices (separated by whitespace), choosing each index i with probability proportional to ai.
So far I have
public static void main(String[] args) {
// number of random indices
int m = Integer.parseInt(args[0]);
// read in frequency of occurrence of n values
int n = args.length;
int[] freq = new int[n];
for (int i = 0; i < n; i++) {
freq[i] = Integer.parseInt(args[i]);
}
// compute total count of all frequencies
int total = 0;
for (int i = 0; i < n; i++) {
total += freq[i];
}
for (int j = 0; j < m; j++) {
// generate random integer with probability proportional to frequency
int r = (int) ((total) * Math.random() - 1); // integer in [0, total)
int sum = 0;
int event = -1;
for (int i = 0; i < n && sum <= r; i++) {
sum += freq[i];
event = i;
System.out.println(freq[i]);
}
}
}
Under the assumption that I understand your problem correctly, then you can use the following algorithm to produce m random numbers in the range 1 to n according to the given frequencies:
public static void main(String[] args) {
// number of random indices
int m = Integer.parseInt(args[0]);
// read in frequency of occurrence of n values
int n = args.length;
int[] freq = new int[n];
for (int i = 1; i < n; i++) {
freq[i] = Integer.parseInt(args[i]);
}
// compute total count of all frequencies
int total = 0;
for (int i = 1; i < n; i++) {
total += freq[i];
}
double[] summedProbabilities = new double[n];
for (int i = 1; i < summedProbabilities.length; i++) {
final double probability = freq[i] / (double) total;
summedProbabilities[i] = summedProbabilities[i -1] + probability;
}
for (int j = 0; j < m; j++) {
// generate random integer with probability proportional to frequency
double randomProbability = Math.random();
int i = 1;
while (randomProbability > summedProbabilities[i]) {
i++;
}
System.out.print(i + " ");
if (j % 10 == 0) {
System.out.println();
}
}
}
I strongly suggest you to refactor the code in a way that you use methods to calculate small pieces and compose it then.
public class DiscreteDistribution{
public static void main(String[] args) {
// takes in number of times we must loop to print indices
int m = Integer.parseInt(args[0]);
// set the array size to the number of input from command line
//minus the first input
//because we are not considering the input at args[0]
int [] n = new int[args.length-1];
// cSum to store the cummulatives
int [] cSum = new int[args.length];
// to store an array of random generated
//number of size m
int [] rand = new int[m];
int count = 1;
int cCount = 1;
int sum = 0; // to add the inputs n;
// to store user input in an array in n ignoring the first input
for(int i =0; i < n.length; i++)
{
n[i] = Integer.parseInt(args[count]);
count++;
}
//stores the cummulatives of n in cSum
for(int j = 0; j < n.length; j++)
{
sum = sum + n[j];
cSum[j+1] = sum;
}
//generate a random number and stores in rand representing the //probabilites
for(int p = 0; p < m; p++) {
int r = (int)(1+Math.random()*cSum[cSum.length-1]);
rand[p] = r;
}
// loop from 0 to m to print the indices of n;
for(int s = 0; s < m; s++) {
//prints the indices corresponding to the condition
for(int q = 1; q < n.length; q++) {
if(rand[s] <= cSum[q-1]) {
System.out.print(q+" ");
}
}
}
}

How to quit scanner when input is negative?

This is the instructions.
Write a program that reads a sequence of input values and displays a bar chart of the values using asterisks. You may assume that all values are positive. First figure out the maximum value. That's value's bar should be drawn with 40 asterisks. Shorter bars should use proportionally fewer asterisks.
This is what I came up so far. It's all good except I need to enter a letter instead of a negative number to quit scanning. I have tried (if( < 0) things) but those didn't work.
import java.util.Scanner;
public class BarChart1 {
public static void main(String [] args) {
int[] arr = new int[100];
int currentSize = 0;
System.out.println("Enter a sequence of positive integers. "
+ ("Enter a negative value to quit:"));
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
int num = in.nextInt();
if (num < 0) {
break;
}
else {
arr[currentSize] = in.nextInt();
currentSize++;
}
}
//will find the max
double max = arr[0];
int y = 0;
for (int i = 1; i < arr.length; i++) {
y = i + 1;
if(max < arr[i]) {
max = arr[i];
//y = i + 1;
}
}
System.out.println("Max number is: " + max);
System.out.println("Number of digits = " + y);
System.out.println(Math.abs(-1));
double scale = 40/max;
System.out.println("Scale = " + scale);
for (int i = 0; i < y; i++) {
double h = scale * arr[i];
if (h != 0) {
for (int j = 1; j <= h; j ++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
This is the result.
1
2
3
4
-1
Max number is: 4.0
Number of digits = 100
Scale = 10.0
********************
****************************************
I only need the asterisks. Everything else that is being printed is just for checking purposes.
You can try this:
while(in.hasNextInt()) {
int num =in.nextInt();
if(num <0){
break;
}
else{
arr[currentSize] = num;
currentSize++;
}
}

Direction Array: reducing complexity

I have a m*n matrix where every element is unique. From a given starting point I have to move to the smallest point(up, down, left, right)and then have to do the same process again. When all other surrounding point is greater than the existing one I have to stop and print the position from start. suppose I have a matrix(5*5)
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
and starting point is (2,2) then the output will be 13,8,3,2,1.
I have solved this problem my way, But the problem is its complexity. I do not think my solution is efficient. Can anyone suggest me any better solution?
N.B: Except scanner pkg, I am not allowed to import any other pkg. Here is my code:
import java.util.Scanner;
public class DirectionArray {
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
int row = in.nextInt();
int col = in.nextInt();
int[][] ara = new int[row][col];
int[] ara2 = new int[4];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
ara[i][j] = in.nextInt();
}
}
System.out.println("Give starting point(x) ");
int x= in.nextInt();
System.out.println("Give starting point(y) ");
int y= in.nextInt();
int sx=x;
int sy =y;
int [] fx={+1,-1,0,0};
int [] fy={0,0,+1,-1};
int p=0;
int l=0;
int v=0;
int r=0;
int [] result=new int[row*col] ;
int min=ara[x][y];
boolean swap=true;
for(int i=0;i<(row*col)-1;i++) {
for (int k = 0; k < 4; k++) {
int nx = x + fx[k];
int ny = y + fy[k];
if (nx >= 0 && nx < row && ny >= 0 && ny < col) {
if (min > ara[nx][ny]) {
ara2[p] = ara[nx][ny];
p++;
}
}
}
p=0;
while(swap) {
swap=false;
r++;
for (int q = 0; q < ara2.length-r; q++) {
if(ara2[q]>ara2[q+1]){
int temp = ara2[q];
ara2[q]=ara2[q+1];
ara2[q+1]=temp;
swap=true;
}
}
}
for(int j=0;j<ara2.length;j++) {
if(ara2[j]!=0)
{
v=ara2[j];
result[l]=v;
l++;
break;
}
}
min=v;
for(int o=0;o<ara2.length;o++) {
ara2[o]=0;
}
for(int m=0;m<row;m++){
for(int n=0;n<col;n++){
if(ara[m][n]==v) {
x = m;
y = n;
}
}
}
I think you need to split up your code in more methods. It would make it easier to read.
For example this is how I would reorganize it:
private static final int[][] COORDINATES_TO_TRY = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int row = in.nextInt();
int col = in.nextInt();
int[][] array = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
array[i][j] = in.nextInt();
}
}
System.out.println("Give starting point(x) ");
int x = in.nextInt();
System.out.println("Give starting point(y) ");
int y = in.nextInt();
findMinimum(array, x, y);
return;
}
private static int[] findMinimum(int[][] array, int x, int y) {
for (int i = 0; true; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(array[x][y]);
int[] coordinates = findLocalMinimum(array, x, y);
if (x == coordinates[0] && y == coordinates[1]) {
return coordinates;
}
x = coordinates[0];
y = coordinates[1];
}
}
private static int[] findLocalMinimum(int[][] array, int x, int y) {
int min = array[x][y];
int minX = x;
int minY = y;
for (int[] coordinates : COORDINATES_TO_TRY) {
int i = x + coordinates[0];
int j = y + coordinates[1];
if (i >= 0 && i < array.length && j >= 0 && j < array[i].length) {
if (array[i][j] < min) {
minX = i;
minY = j;
min = array[i][j];
}
}
}
return new int[]{minX, minY};
}

Lagrange interpolation in JAVA

I have done a search around, but there isnt any code available in java hence I have write my own and I have encountered some issue. I actually got this code from a c++ source and trying hard to convert it into a workable java program.
http://ganeshtiwaridotcomdotnp.blogspot.sg/2009/12/c-c-code-lagranges-interpolation.html
public static void main(String[] args) {
int n;
int i, j;
int a;
int x[] = null;
int f[] = null;
int sum = 0;
int mult;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of point: ");
n = input.nextInt();
System.out.println("Enter value x for calculation: ");
a = input.nextInt();
for (i = 0; i < n; i++) {
System.out.println("Enter all values of x and corresponding functional vale: ");
x = input.nextInt();
f = input.nextInt();
}
for (i = 0; i <= n - 1; i++) {
mult = 1;
for (j = 0; j <= n - 1; j++) {
if (j != i) {
mult *= (a - x[j]) / (x[i] - x[j]);
}
sum += mult * f[i];
}
}
System.out.println("The estimated value of f(x)= " + sum);
}
For Lagrange Interpolation Formula -
You should use double data type Array
Your should make Arrays with specific number of items
Look at the program below, you will understand.
double product, sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Number of Terms: ");
int n = sc.nextInt();
double[] x = new double[n];
double[] y = new double[n];
System.out.println("Enter all the x, y terms: ");
for (int i = 0; i < n; i++) {
x[i] = sc.nextDouble();
y[i] = sc.nextDouble();
}
System.out.println("x = {" + Arrays.toString(x) + "}");
System.out.println("x = {" + Arrays.toString(y) + "}");
System.out.print("Enter a point to Find it's value: ");
int xPoint = sc.nextInt();
// End of inputs
product = 1;
// Peforming Arithmatic Operation
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j != i) {
product *= (xPoint - x[j]) / (x[i] - x[j]);
}
}
sum += product * y[i];
product = 1; // Must set to 1
}
System.out.println("The value at point " + xPoint + " is : " + sum);
// End of the Program
}
}
int x[] = null;
int f[] = null;
...
for (i = 0; i < n; i++) {
....
x = input.nextInt();
f = input.nextInt();
}
Looks clear enough. Simply create array instance for x and f:
x = new int[n];
f = new int[n];
Somewhere after:
n = input.nextInt();
Before above for loop, and modify the for body:
...
x[i] = input.nextInt();
f[i] = input.nextInt();
public static void main(String[] args) {
System.out.println("Langrages");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no of terms: ");
int n = sc.nextInt();
float[] ax = new float[n];
System.out.println("Enter values of x");
for(int i=0 ;i<n;i++) {
ax[i] = sc.nextFloat();
}
float[] ay = new float[n];
System.out.println("Enter values of y");
for(int i=0 ;i<n;i++) {
ay[i] = sc.nextFloat();
}
System.out.println("Enter the value of x\n at which you find y");
int x = sc.nextInt();
float num,den;
float term =0;
for(int i=0;i<n;i++) {
num=1;
den=1;
for(int j=0;j<n;j++) {
if(j!=i) {
num=num*(x-ax[j]);
den = den*(ax[i]-ax[j]);
}
}
term += (num/den)*ay[i];
}
System.out.println(term);
sc.close();
}

Categories

Resources