ArrayList in Java that lists square numbers - Homework - java

I think I have most of the code figured out, there is just one part that is giving me grief. When I use printList(list) it prints out 1, 2, 3,... up to 9 when it is supposed to be printing the squares of these numbers. If I print out the createSquaresList(10) it is correctly printed. Any help is appreciated :-).
import java.util.*;
public class Lab8a
{
public static void main(String args[])
{
ArrayList<Double> list = createSquaresList(10);
printList(list);
removeElement(list, 4);
printList(list);
swapElements(list, 2, 6);
printList(list);
double max = getMaxValue(list);
double ave = getAverage(list);
System.out.println("Max Value = " + max);
System.out.println("Average = " + ave);
int idx1 = linearSearch(list, 4);
int idx2 = linearSearch(list, 75);
System.out.println("idx 1 = " + idx1);
System.out.println("idx 2 = " + idx2);
}
public static ArrayList<Double> createSquaresList(int n)
{
ArrayList<Double> squares= new ArrayList<>();
double s = 0.0;
for (double i = 0.0; i <= n-1; i++)
{
s = i*i;
squares.add(s);
}
return squares;
}
public static double getMaxValue(ArrayList<Double> list)
{
double largest = list.get(0);
for (int i = 1; i < list.size(); i++)
{
if (list.get(i) > largest)
{
largest = list.get(i);
}
}
return largest;
}
public static double getAverage(ArrayList<Double> list)
{
double avg = 0.0;
double sum = 0.0;
for (int i =0; i < list.size(); i++)
{
sum += list.get(i);
}
avg = sum / list.size();
return avg;
}
public static void removeElement(ArrayList<Double> list, double index)
{
double temp = 0.0;
int lastPos = list.size() - 1;
double last = list.get(lastPos);
index = temp;
temp = last;
last = index;
list.remove(lastPos);
}
public static void swapElements(ArrayList<Double> list, int a, int b)
{
int temp = 0;
a = temp;
temp = b;
b = a;
}
public static int linearSearch(ArrayList<Double> list, double val)
{
int pos = 0;
boolean found = false;
while (pos < list.size() && !found)
{
if (list.get(pos) == val)
{
found = true;
}
else
{
pos++;
}
}
if (found)
{
return pos;
}
else
{
return -1;
}
}
public static void printList(ArrayList<Double> list)
{
for(int i = 0; i < list.size(); i++)
{
System.out.print(i);
if(i < list.size()-1)
{
System.out.print(", ");
}
}
System.out.println("");
}
}

Change
System.out.print(i);
to
System.out.print(list.get(i));

it is because you are print the int not the contents of the list,
try changing the 3 line of the function printList to:
System.out.print(list.get(i));

Related

code sends one big array to hireAssistant but I want to send individual permutations one by one

public static int [] makeArray(int n){
int arr[] = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
return arr;
}
public static int hireAssistant1(int[] arr, int n) {
ArrayList<Integer> hired = new ArrayList<Integer>();
int best = arr[0];
hired.add(best);
for (int i = 1; i < n; i++) {
if (arr[i] < best) {
best = arr[i];
hired.add(best);
}
}
return hired.size();
}
public static void methodThreePerm(List<Integer> list, int n) {
int size = factorial(n);
int [] arr = new int [list.size()];
arr = toIntArray(list);
double sum = 0;
for (int i = 0; i < size; i++) {
int hires = hireAssistant1(arr, n);
if (hires == 2)
sum = sum + 1;
}
System.out.println("Method 3: s/n! = " + sum /size);
}
public static int factorial(int n) {
if (n == 1) return 1;
if (n == 0) return 1;
if (n == 2) return 2;
return n * factorial(n - 1);
}
static int[] toIntArray(List<Integer> list) {
int[] ret = new int[list.size()];
for(int i = 0; i < ret.length; i++)
ret[i] = list.get(i);
return ret;
}
static List<Integer> listToList(List<List<Integer>> list) {
List<Integer> flat =
list.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
return flat;
}
public List<List<Integer>> permute(int[] arr) {
List<List<Integer>> list = new ArrayList<>();
permuteHelper(list, new ArrayList<>(), arr);
return list;
}
private void permuteHelper(List<List<Integer>> list, List<Integer> resultList, int[] arr) {
if (resultList.size() == arr.length) {
list.add(new ArrayList<>(resultList));
} else {
for (int i = 0; i < arr.length; i++) {
if (resultList.contains(arr[i])) {
continue;
}
resultList.add(arr[i]);
permuteHelper(list, resultList, arr);
resultList.remove(resultList.size() - 1);
}
}
}
public static void main(String[] args) {
Assignment8 pa = new Assignment8();
int n = 6;
List<List<Integer>> p = pa.permute(makeArray(n));
List<Integer> list = listToList(p);
System.out.println("N = 6");
methodThreePerm(list, n);
The expectation is to enumerate all the n! permutations of the arrays of ranks,
check 𝑠 - the number of arrays where we hire exactly
twice, and output the probability: 𝑠/𝑛!.
I have added the base methods needed to check any array, but cant seem to figure out how to send an array of permutations to my hire Assistant method to check for each hire
static void methodOneSum1(int n) {
double sum = 0;
for (double i = 2; i <= n; i++)
sum += 1 / ((double) (i - 1));
System.out.println("Method 1: n = " + (sum / n));
}
this output for this is when n = 6
Method 1: n = 0.38055555555555554
which is supposed to equal the methodThreePerm
Stick with using lists instead of converting to arrays to simplify your logic and send the list of lists to methodThreePerm so that you can send the individual permutations to hireAssistant.
public static int [] makeArray(int n){
return IntStream.iterate(1, i -> ++i).limit(n).toArray();
}
public static int hireAssistant1(List<Integer> arr, int n) {
ArrayList<Integer> hired = new ArrayList<Integer>();
int best = arr.get(0);
hired.add(best);
for (int i = 1; i < n; i++) {
if (arr.get(i) < best) {
best = arr.get(i);
hired.add(best);
}
}
return hired.size();
}
public static void methodThreePerm(List<List<Integer>> list, int n) {
int size = factorial(n);
double sum = 0;
for (List<Integer> arr : list) {
int hires = hireAssistant1(arr, n);
if (hires == 2)
++sum;
}
System.out.println("Sum:" + sum);
System.out.println("Size:" + size);
System.out.println("Method 3: s/n! = " + sum /size);
}
public static int factorial(int n) {
if (n == 1) return 1;
if (n == 0) return 1;
if (n == 2) return 2;
return n * factorial(n - 1);
}
public List<List<Integer>> permute(int[] arr) {
List<List<Integer>> list = new ArrayList<>();
permuteHelper(list, new ArrayList<>(), arr);
return list;
}
private void permuteHelper(List<List<Integer>> list, List<Integer> resultList, int[] arr) {
if (resultList.size() == arr.length) {
list.add(new ArrayList<>(resultList));
} else {
for (int i : arr) {
if (resultList.contains(i)) {
continue;
}
resultList.add(i);
permuteHelper(list, resultList, arr);
resultList.remove(resultList.size() - 1);
}
}
}
public static void main(String[] args) {
Assignment8 pa = new Assignment8();
int n = 6;
List<List<Integer>> p = pa.permute(makeArray(n));
System.out.println("N = 6");
methodThreePerm(p, n);
}
Prints:
N = 6
Sum:197280.0
Size:720
Method 3: s/n! = 274.0

Is there a way to display the users input back to them before displaying the mean and median?

I am working with the following code that allows the user to enter 9 numbers and it displays the mean and median of the numbers back to the user. I am trying to figure out the best way to revise my code so that before displaying the mean and median it will also show the 9 numbers the user entered. Thanks so much for any help in this matter!
import java.util.*;
class MeanMedian
{
private static float mean(int arr[]){
int n = arr.length;
float sum = 0;
for(int i = 0;i<n;i++){
sum += arr[i];
}
return sum / n;
}
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int lowindex = i;
for (int j = array.length - 1; j > i; j--)
if (array[j] < (array[lowindex]))
lowindex = j;
int temp = array[i];
array[i] = array[lowindex];
array[lowindex] = temp;
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static float median(int arr[]){
selectionSort(arr);
if(arr.length%2 == 0){
return arr[(arr.length/2)-1];
}
else{
return arr[arr.length/2];
}
}
public static void main(String args[]){
int n = 9;
Scanner scanner = new Scanner(System.in);
int arr[] = new int[n];
System.out.print("Enter "+ n +" integers: ");
for(int i = 0;i<n;i++){
arr[i] = scanner.nextInt();
}
System.out.println("mean: "+ mean(arr));
System.out.println("median: "+ median(arr));
}
}
I am trying to figure out the best way to revise my code so that
before displaying the mean and median it will also show the 9 numbers
the user entered.
Something like:
// ... previous code ...
System.out.println("You entered: ");
for(int i : arr) {
System.out.println(i);
}
System.out.println("mean: "+ mean(arr));
System.out.println("median: "+ median(arr));
The following code worked perfectly and passed all checks I ran on it :)
import java.util.*;
class MeanMedian
{
private static float mean(int arr[]){
int n = arr.length;
float sum = 0;
for(int i = 0;i<n;i++){
sum += arr[i];
}
return sum / n;
}
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int lowindex = i;
for (int j = array.length - 1; j > i; j--)
if (array[j] < (array[lowindex]))
lowindex = j;
int temp = array[i];
array[i] = array[lowindex];
array[lowindex] = temp;
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static float median(int arr[]){
selectionSort(arr);
if(arr.length%2 == 0){
return arr[(arr.length/2)-1];
}
else{
return arr[arr.length/2];
}
}
public static void main(String args[]){
int n = 9;
Scanner scanner = new Scanner(System.in);
int arr[] = new int[n];
System.out.print("Enter "+ n +" integers: ");
for(int i = 0;i<n;i++){
arr[i] = scanner.nextInt();
}
System.out.println("You entered: ");
for(int i : arr) {
System.out.println(i);
}
System.out.println("mean: "+ mean(arr));
System.out.println("median: "+ median(arr));
}
}

Calculate distance between nodes in AdjacencyMatrix

I have implemented AdjacencyMatrix in java, but I am having hard time implementing the distance() method to be able to find the distance between two nodes.
Any idea how I an do that?
I have tried a lot of things but I don't seem to be able to get right answer.
Here's my implementation
public class AdjacencyMatrix implements Representation {
private Node[] nodes;
private int[][] adjacencyMatrix;
private int numberOfNodes =0;
public AdjacencyMatrix(File file) {
Scanner inFile;
int numNodes;
try {
inFile = new Scanner(file);
numNodes = Integer.parseInt(inFile.nextLine());
adjacencyMatrix = new int[20][20];
nodes = new Node[20];
String[] line;
while (inFile.hasNextLine()) {
line = inFile.nextLine().split(":");
Node from = new Node(Integer.parseInt(line[0]));
Node to = new Node(Integer.parseInt(line[1]));
int value = Integer.parseInt(line[2]);
if(!Arrays.asList(nodes).contains(from))
addNode(from);
if(!Arrays.asList(nodes).contains(to))
addNode(to);
addEdge(new Edge(from, to, value));
}
} catch (FileNotFoundException e) {
System.out.print(e.getCause());
}
}
public AdjacencyMatrix() {
}
#Override
public boolean adjacent(Node x, Node y) {
int fromIndex = findIndex(x);
int toIndex = findIndex(y);
if(adjacencyMatrix[fromIndex][toIndex] == 1 || adjacencyMatrix[toIndex][fromIndex] ==1){
return true;
}
return false;
}
#Override
public List<Node> neighbors(Node x) {
ArrayList<Node> neighbors = new ArrayList<>();
int fromIndex = findIndex(x);
if(x.getData().toString().equals("4")) {
System.out.println("FromIndex is: " + fromIndex);
}
if(x.getData().toString().equals("4")){
for(int i =0; i < nodes.length; ++i){
System.out.println(nodes[i] + " ");
}
}
for (int i = 0; i <= numberOfNodes; i++){
if(adjacencyMatrix[fromIndex][i] == 1){
neighbors.add(nodes[i]);
if(x.getData().toString().equals("4")) {
System.out.println("Match!: " + i);
System.out.println("Adding NODE: " + nodes[i]);
}
}
}
int [] nums = new int[neighbors.size()];
for(int i =0; i < nums.length; ++i){
nums[i] = Integer.parseInt(neighbors.get(i).getData().toString());
}
Arrays.sort(nums);
ArrayList<Node> newNeighbors = new ArrayList<>();
for(int i =0; i < nums.length; ++i){
newNeighbors.add(new Node(nums[i]));
}
return newNeighbors;
}
#Override
public boolean addNode(Node x) {
if(Arrays.asList(nodes).contains(x)){
return false;
}
nodes[numberOfNodes] = x;
for (int i = 0; i <= numberOfNodes; i++){
adjacencyMatrix[numberOfNodes][i] = 0;
adjacencyMatrix[i][numberOfNodes] = 0;
}
numberOfNodes++;
return true;
}
#Override
public boolean removeNode(Node x) {
if (!Arrays.asList(nodes).contains(x)) {
return false;
}
for (int k = 0; k < numberOfNodes; k++) {
if (x.equals(nodes[k])) {
//decrement the number of nodes
numberOfNodes--;
for (int i = k; i < numberOfNodes; i++) {
nodes[i] = nodes[i + 1];
}
for (int i = k; i < numberOfNodes; i++) {
for (int j = 0; j <= numberOfNodes; j++) {
adjacencyMatrix[i][j] = adjacencyMatrix[i + 1][j];
}
}
for (int i = k; i < numberOfNodes; i++) {
for (int j = 0; j < numberOfNodes; j++) {
adjacencyMatrix[j][i] = adjacencyMatrix[j][i + 1];
}
}
}
//
}
return true;
}
#Override
public boolean addEdge(Edge x){
int from = Integer.parseInt(x.getFrom().getData().toString());
int to = Integer.parseInt(x.getTo().getData().toString());
int fromIndex = findIndex(x.getFrom());
int toIndex = findIndex(x.getTo());
if(from == 4){
System.out.println("Adding adjecent to 4 -> " + to);
}
if(adjacencyMatrix[fromIndex][toIndex] == 1 ){
return false;
}
adjacencyMatrix[fromIndex][toIndex] = 1;
return true;
}
#Override
public boolean removeEdge(Edge x) {
int from = Integer.parseInt(x.getFrom().getData().toString());
int to = Integer.parseInt(x.getTo().getData().toString());
int fromIndex = findIndex(x.getFrom());
int toIndex = findIndex(x.getTo());
if(adjacencyMatrix[fromIndex][toIndex] == 0 && adjacencyMatrix[toIndex][fromIndex] ==0){
return false;
}
adjacencyMatrix[fromIndex][toIndex] = 0;
return true;
}
#Override
public int distance(Node from, Node to) {
return 0;
}
#Override
public Optional<Node> getNode(int index) {
return null;
}
#Override
public Collection<Node> getNodes() {
return Arrays.asList(nodes);
}
public int findIndex(Node node)
{
for (int i = 0; i < numberOfNodes; ++i)
if (nodes[i].equals(node))
return i;
return -1;
}}
All my methods are working except distance().
I am returning 0 in the distance() method since I don't know how to implement it correctly.
Any help would be greatly appreciated.
I figured it out.
Basically I made an array to keep track of my Edges:
private Edge [] edges;
Then I populated the array with my graph edges.
Now, in my distance method I just find the edge with the give To and From Nodes, and extract it's value which is the distance I'm looking for :)
public int distance(Node from, Node to) {
for(Edge edge: edges){
if(edge.getFrom().equals(from) && edge.getTo().equals(to)){
return edge.getValue();
}
}
return 1;
}
I must have thought about this simple solution earlier!

I would like to make my code more implementable for other applications

I would like to make my code more implementable for others applications.
I don't have problems with the code, it works perfectly. I would just like to rewrite it to use it in other contexts.
My original code:
import java.util.concurrent.*;
class Sum extends RecursiveTask<Double> {
final int seqThresHold = 500;
double[] data;
int start, end;
Sum(double[] vals, int s, int e ) {
data = vals;
start = s;
end = e;
}
protected Double compute() {
double sum = 0;
if((end - start) < seqThresHold) {
for(int i = start; i < end; i++) sum += data[i];
}
else {
int middle = (start + end) / 2;
Sum subTaskA = new Sum(data, start, middle);
Sum subTaskB = new Sum(data, middle, end);
subTaskA.fork();
subTaskB.fork();
sum = subTaskA.join() + subTaskB.join();
}
return sum;
}
}
class RecurTaskDemo {
public static void main(String args[]) {
ForkJoinPool fjp = new ForkJoinPool();
double[] nums = new double[5000];
for(int i=0; i < nums.length; i++)
nums[i] = (double) (((i%2) == 0) ? i : -i) ;
Sum task = new Sum(nums, 0, nums.length);
double summation = fjp.invoke(task);
System.out.println("Summation " + summation);
}
}
The new code I would like to get:
public class RecurTaskDemo {
private static double Sum(double[] data, int start, int end) {
double sum = 0;
for (int i = start; i < end; i++) {
sum += data[i];
}
return sum;
}
// ???
public static void main(String args[]) {
double[] nums = new double[4000];
for (int i = 0; i < nums.length; i++)
nums[i] = (double) (((i % 2) == 0) ? i : -i);
double sum = Sum(nums, 0, 4000);
// double sum = ... I would like to calculate 'sum' using 'Sum(...)' + '???'
System.out.println(sum);
}
}

Method returning null pointer error

There is the error I am getting
Exception in thread "main" java.lang.NullPointerException
at StudentGrades.getMinimum(StudentGrades.java:54)
at StudentClient.main(StudentClient.java:14)
I did not find any method that i set a null.
I tried using median method but still gets me this same error.
import java.util.Arrays;
import java.util.Random;
public class StudentGrades {
Random randomNumber = new Random();
int numberofStudents;
int grade;
int[] grades;
int sum = 0;
public StudentGrades(int studentNumber) {
numberofStudents = studentNumber;
int[] grades = new int[numberofStudents];
for (int i = 0; i < numberofStudents; i++) {
grades[i] = randomNumber.nextInt(101);
Arrays.sort(grades);
}
}
public int getNumberStudents() {
return numberofStudents;
}
public int[] getStudentGrades() {
int[] temp = new int[grades.length];
for (int i = 0; i < grades.length; i++) {
temp[i] = grades[i];
}
return temp;
}
public void setStudentGrades(int n) {
grade = n;
}
public double getAverage() {
for (int i = 0; i < grades.length; i++) {
sum = +grades[i];
}
double average = (double) sum / numberofStudents;
return average;
}
public int getMaximum() {
int max = grades[0];
for (int i = 0; i < grades.length; i++) {
if (grades[i] > grades[max])
max = grades[i];
}
return max;
}
public int getMinimum() {
int min = grades[0];
for (int i = 0; i < grades.length; i++) {
if (grades[i] < grades[min])
min = grades[i];
}
return min;
}
public String toString() {
String returnString = "grades :";
for (int i = 0; i < grades.length; i++) {
returnString += grades[i];
}
return returnString;
}
public double getMedian() {
double median = 0;
if (grades.length % 2 == 0) {
median = (grades[grades.length / 2] + grades[(grades.length / 2) + 1]) / 2;
} else
median = grades[((grades.length - 1) / 2) + 1];
return median;
}
}
In your constructor you declared a local variable grades which did not initialize your instance variable grades:
int [] grades = new int [numberofStudents];
So the instance variable grades remains null. Try this:
grades = new int [numberofStudents];
which refers to the instance variable instead of declaring a local variable.

Categories