how to fill array with given values - java

i have to get a sequence of numbers and count how many times it takes and then put it into an array so i can sort the array and look for the 10th largest. I can get the count but cant seem to fill the array, i either put in the final count at every index in the array or i just increase the value of the array at index 0 to the count of all numbers, can anyone help.
public class seBuilder
{
//int count=0;
//int [] myArray= new int[10];
public static void main (String args[])
{
int count=0;
int [] myArray= new int[13];
int z=0;
for(int i=2;i<=myArray.length;i++)
{
z=valuegetter(i);
System.out.println(z);
}
//arraycounter(myArray, z);
}
public static int valuegetter(int num)
{
int count=0;
do// do while loop
{
//if its an odd number
if(num%2==1){
num=(num*3)+1;//do this from the question
count++;// add one to count
}
//if num is 2 this will catch and make the code break out
else if(num==2){
//devide num by 2, this will give you 1 allways
System.out.println(num/2);
count++;//adds 1 again
}
else
{
num=num/2;//this will use if number is even
count++;//adds one to count
}
}
while(num>2);//the condition to jump out of loop
//System.out.println("there are "+count+" sequences in that mumber");
return count;
}
public static int[] arraycounter(int myArray[], int count)
{
for(int i=0;i<=myArray.length-1;i++)
{
myArray[i]=count;
System.out.println(" "+myArray[i]);
}
return myArray;
}
public static int tenhigh()
{
}
}

Try to change your main to this:
public static void main (String args[])
{
int count=0;
int [] myArray= new int[13];
int z=0;
for(int i=2;i<=myArray.length;i++) {
z=valuegetter(i);
System.out.println(z);
arraycounter(myArray, z, i);
}
for (int i=0; i < myArray.length; i++) {
System.out.print(myArray[i] + ", ");
}
}
Also change your arrayCounter method to this:
public static int[] arraycounter(int myArray[], int count, int i)
{
int j = i - 2;
myArray[j] = count;
return myArray;
}

If you want to fill an array with a given value, use Arrays.fill, from the java.utils.Arrays class.

Related

Given an “Adjacency Matrix” representation of a an undirected graph BFS on the graph and output the vertex

I can find BFS and DFS values in a two-dimensional array array, but there is no increase in scoring. I could not figure out exactly which part I did wrong. When I print the values that should be, the sort is correct. but the grade is still 0. I am open to your ideas.
public class BFS_DFS {
public static int[] BFS (int [][] graph) {
int[] output = {0};
int start=0;
int v=graph.length;//a[][] is adj matrix declared globally
boolean visited[]=new boolean[v];//indexing done from 1 to n
LinkedList<Integer> queue=new LinkedList<Integer>();
visited[start]=true;
queue.add(start);
while(queue.size()!=0)
{
int x=queue.remove();
System.out.print(x+" ");
for(int j=graph.length;j<graph.length;j++){
output[j-1]=x;
}
for (int i=1; i < v; i++)
if((graph[x][i] == 1) && (!visited[i]))
{
queue.add(i);
visited[i]=true;
}
}
return output ;
}
public static void main(String[] args) {
//DO NOT WRITE ANY CODE IN MAIN METHOD
int [][] graph={{0,1,1,1,0,0},{1,0,0,0,1,1},{1,0,0,0,0,1},{1,0,0,0,0,0},{0,1,0,0,0,0},{0,1,1,0,0,0}};
int [] BFSresult={0,1,2,3,4,5};
int [] DFSresult={0,1,4,5,2,3};
int grade=0;
if (Arrays.equals(BFS(graph),BFSresult )) {
System.out.println("BFS is working correctl");
grade+=50;
}
else
System.out.println("BFS is not working correctly");
if (Arrays.equals(DFS(graph),DFSresult )) {
System.out.println("DFS is working correctl");
grade+=50;
}
else
System.out.println("DFS is not working correctly");
System.out.println("Your grade is->"+grade);
}
}
Array (int[] output) is not appropriate to store results of un-known length, because it has a fixed length.
Use a collection like List instead:
public static int[] BFS (int [][] graph) {
//you do not know what is the path length so use a List
List<Integer> output = new ArrayList<>();
int start=0;
int v=graph.length;
boolean visited[]=new boolean[v];//indexing done from 1 to n
LinkedList<Integer> queue=new LinkedList<>();
visited[start]=true;
queue.add(start);
while(queue.size()!=0)
{
int x=queue.remove();
System.out.print(x+" ");
output.add(x); //add to output
for (int i=1; i < v; i++) {
if((graph[x][i] == 1) && (!visited[i]))
{
queue.add(i);
visited[i]=true;
}
}
}
//convert back to array
return output.stream().mapToInt(Integer::intValue).toArray();
/*if you can't use java 8 stream, convert output to array using:
int[] ret = new int[output.size()];
int i = 0;
for (int e : output) { ret[i++] = e; }
return ret;
*/
}

finding the average of array then finding the number above the average to print

import java.util.Scanner;
public class ProjectFour {
public static void main(String args[]) {
int[] firstArray = {1,2,3,2,1,6,3,4,5};
System.out.println("this is the average of array : "+analyzeNumbers(firstArray));
System.out.println("These are the numbers above the average : "+aboveAvg(firstArray));
}
//finding the average
public static int analyzeNumbers(int[] firstArray){
int avg;
avg=sumArray(firstArray);
avg=avg/firstArray.length;
return avg;
}
//suming the array method
public static int sumArray(int[] firstArray){
int sum = 0;
for(int x=0;x<firstArray.length;x++){
sum+=firstArray[x];
}
return sum;
}
**this is where im running into problems im kinda stumpted**
// this is my method i cant figure out trying to take the average and find all the numbers in the array above the average and printing them.
public static int aboveAvg(int[] firstArray){
int[] aboveAvg;
aboveAvg = new int[0];
int x;
for(x=analyzeNumbers(firstArray);x<firstArray.length;x++){
aboveAvg+=firstArray[x];
}
return aboveAvg;
}
}
Try using a for loop.
int sum = 0;
for(int i = 0; i < firstArray; i++) {
int getSum = firstArray.get(i);
sum + getSum;
}
int average = sum / firstArray.length;
int[] aboveAverage;
for(int c = 0; c < firstArray; c++) {
if(firstArray.get(c) > average) {
aboveAverage.add(firstArray.get(c));
}
}
This aboveAvg function is completly wrong.
public static List<Integer> aboveAvg(int[] firstArray){
List<Integer> aboveAvg = new ArrayList<Integer>();
int Avg = analyzeNumbers(firstArray);
for(int i = 0; i<firstArray.length; i++)
{
if(firstArray[i] > Avg)
{
aboveAvg.add(firstArray[i]);
}
}
return aboveAvg;
}
Check your for loop and more examples about it
+= will sum two values, won't add new element on any array.
you have to define your return value correctly.
You can use List for create arrays, it's more flexible.

Why my array class is unable find out the minimum and maximum value of a randomly generated array?

I have created an array with random numbers which will also show maximum and minimum element of the array,the program is successfully compiled.But on run the maximum value:0
minimum value:0
while the generated array is correct.Please help me out to rectify the wrong logic.
class ArrayTest
{
public static void main(String s[])
{
int a[];
a=new int[10];
System.out.println("Storing the random values in Array Elements");
System.out.println("Maximum:"+getMax(a));
System.out.println("Minimum:"+getMin(a));
for(int i=0;i<a.length;i++)
{
a[i]=(int)(Math.random()*100);
}
System.out.println("\n List of Elements:");
int sum=0;
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
//Maximum Value Finding
public static int getMax(int[] a)
{
int max=a[0];
for(int i=0;i<a.length;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
return max;
}
//Minimum Values Finding
public static int getMin(int[] a)
{
int min=a[0];
for(int i=0;i<a.length;i++)
{
if(a[i]<min)
{
min=a[i];
}
}
return min;
}
}
You call the getMax and getMin BEFORE you fill the array.

Sum of squares in an array using function

Question :
Write a program that allows the entry of an integer value n, followed by two sets of n integer values into arrays A and B. The program should use a function to calculate the sum of the square of corresponding values of A and B. These values should then be displayed.
My piece of code :
import java.util.Scanner;
public class Question9_SumOfSquareInArrays {
public static void main(String[] args) {
int sumA = 0;
int sumB = 0;
int n;
int i=0;
Scanner src=new Scanner(System.in);
System.out.print("Please enter value :");
n=src.nextInt();
int [] A=new int[n];
int [] B=new int[n];
System.out.println("Enter value for array A :");
for(i=0;i<n;i++)
{
A[i]=src.nextInt();
}
System.out.println("Enter value for array B :");
for(i=0;i<n;i++)
{
B[i]=src.nextInt();
}
src.close();
System.out.println("Total sum for array A is " + SumOfA(sumA));
System.out.println("Total sum for array B is " + sumOfB(sumB));
}
public static int SumOfA(int sumA)
{
int square=1;
int sum=0;
int n=6;
int [] A= new int[n];
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
public static int sumOfB(int sumB)
{
int square=1;
int n=6;
int sum=0;
int [] B=new int [n];
for(int i=0;i<n;i++)
{
square=B[i]*B[i];
sum+=square;
}
return sum;
}
}
I am not able to find out my mistakes. Can someone please help me?
public static int SumOfA(int sumA)
{
int square=1;
int sum=0;
int n=6;
int [] A= new int[n]; // you are calculating the sum of this array
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
is problematic because it calculates the sum of an array of 0s.
Instead, you need to pass your array to the method, i.e.
in main you need
System.out.println("Total sum for array A is " + SumOfA(A));
and modify your SumOfA as follows. Notice it's better to use n = A.length since the length of A is not necessarily always 6.
public static int SumOfA(int[] A)
{
int square=1;
int sum=0;
int n=A.length; // use length to handle array A of any length
for(int i=0;i<n;i++)
{
square=A[i]*A[i];
sum+=square;
}
return sum;
}
The other method has the same problem

Find majority element in an array in java

I am trying to find out the majority Element in an array ad this code is working fine when I am checking with elements less than size. But it is giving me arrayindexoutofbound exception whenever any element is equal to size of array. Please let me know how to resolve this.
public class MajorityElement {
public static void main(String[] args) {
int a[]={2,2,7,5,2,2,6};
printMajority(a, 7);
}
//1st condition to check if element is in majority.
public static int findCandidate(int a[], int size){
int maj_index=0;
int count =1;
int i;
size=a.length;
for(i=1;i<a.length;i++ ){
if(a[maj_index]==a[i])
count++;
else
count--;
if(count==0)
{
maj_index=a[i]; //current element takes max_inex position.
count =1;
}
}
return a[maj_index];
}
public static boolean isMajority(int a[], int size, int cand){
int i, count =0;
for(i=0;i<a.length;i++)
{
if(a[i]==cand)
count++;
}
if(count>size/2){
return true;
}
else {
return false;
}
}
private static void printMajority(int a[],int size){
size=a.length;
int cand=findCandidate( a, 7);
if(isMajority(a,size,cand))
System.out.printf("%d",cand);
else
System.out.println("no such element as majority");
}
}
The problem is in the maj_index=a[i]; line. You take the value of one of the cells of the array and assign it to maj_index which is subsequently used as an index into the array (see a[maj_index] == a[i]). Thus, if the value at that position was larger than the size of the array an out-of-bounds situation will occur.
Here's your code slightly revised. In particular, I got rid of the maj_index variable so that the index vs. value mixup cannot happen. I also used a for-each loop for (int current : a) instead of the for-loop for(int i = 0; i < a.length; ++i). Finally, I eliminated the the size parameter (no need to pass it, it can be inferred from the array itself via a.length)
public class MajorityElement {
// 1st condition to check if element is in majority.
public static int findCandidate(int a[]) {
int cand = a[0];
int count = 1;
for (int i = 1; i < a.length; i++) {
if (cand == a[i])
count++;
else
count--;
if (count == 0) {
cand = a[i];
count = 1;
}
}
return cand;
}
public static boolean isMajority(int a[], int cand) {
int count = 0;
for (int current : a) {
if (current == cand)
count++;
}
return count > a.length / 2;
}
private static void printMajority(int a[]) {
int cand = findCandidate(a);
if (isMajority(a, cand))
System.out.printf("%d", cand);
else
System.out.println("no such element as majority");
}
public static void main(String[] args) {
int a[] = { 9, 7, 9, 5, 5, 5, 9, 7, 9, 9, 9, 9, 7 };
printMajority(a);
}
}
Problem is with your :
for(i=1;i<a.length;i++ ){
if(a[maj_index]==a[i])
count++;
else
count--;
if(count==0)
{
maj_index=a[i]; //current element takes max_inex position.
count =1;
}
}
return a[maj_index];
here you are getting the value as like :a[maj_index] for a test data int a[]={2,1,8,8,8,8,6}; the elemnt 8 is the major but a[maj_index] is invalid which is causing the issue,
Instead Complete code can be like below:
public class TestMajor {
/**
* #param args
*/
public static void main(String[] args) {
int a[]={2,1,8,8,8,8,6};
printMajority(a, 7);
}
//1st condition to check if element is in majority.
public static int findCandidate(int a[], int size){
int test = a[0];
int count =1;
int i;
size=a.length;
for(i=1;i<a.length;i++ ){
if(test ==a[i])
count++;
else
count--;
if(count==0)
{
test =a[i]; //current element takes max_inex position.
count =1;
}
}
return test;
}
public static boolean isMajority(int a[], int size, int cand){
int i, count =0;
for(i=0;i<a.length;i++)
{
if(a[i]==cand)
count++;
}
if(count>size/2){
return true;
}
else {
return false;
}
}
private static void printMajority(int a[],int size){
size=a.length;
int cand=findCandidate( a, 7);
if(isMajority(a,size,cand))
System.out.printf("%d",cand);
else
System.out.println("no such element as majority");
}
}
Majority Element in an Array using Java 8 OR Find the element appeared max number of times in an array :
public class MajorityElement {
public static void main(String[] args) {
int[] a = {1,3,4,3,4,3,2,3,3,3,3,3};
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
Map<Integer, Long> map = list.parallelStream()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println("Map => " + map);
//{1=1, 2=1, 3=8, 4=2}
map.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))//compare the values and get the maximum value
.map(Entry::getKey)// get the key appearing maximum number of times
.ifPresentOrElse(System.out::println,() -> new RuntimeException("no such thing"));
/*
* OUTPUT : Map => {1=1, 2=1, 3=8, 4=2}
* 3
*/
System.out.println("...............");
// A very simple method
//method 2
Integer maxAppearedElement = list.parallelStream().max(Comparator.comparing(Integer::valueOf)).get();
System.out.println(maxAppearedElement);
}//main
}

Categories

Resources