Operations on 1 Dimensional arrays - java

I am learning operations on 1 dim array.
It has three parts:
Set the 10 elements of integer array counts to zero.
Add one to each of the 15 elements of integer array bonus.
Display the five values of integer array best Scores in column format.
I have already figured out the 3. I need help in figuring out 1 and 2.
This is my code:
public class OneDimArrayOperations {
public static void main(String [] args){
// a) Set the 10 elements of integer array counts to zero.
int [] zeroArray = new int[10];
for (int i = 10; i == 0; i--) {
System.out.println("Count to zero from 10 elements" + zeroArray);
}
// b) Add one to each of the 15 elements of integer array bonus.
int [] arrayBonus = new int[15];
for (int i = 0; i <arrayBonus.length; i++) {
System.out.println("Bonus array values "+ arrayBonus[i]);
}
//c) Display the five values of integer array bestScores in column format.
int [] bestScores = {100,95,85,45,65};
System.out.printf("%n%s%12s %n", "Value", "BestScores");
for (int counter = 0; counter < bestScores.length ; counter++) {
System.out.printf( "%d%9d%n" , counter , bestScores[counter]);
}
}
}

part a:display:10,9,8,7,....1,0
for(int i=10;i>=0;i--)
part b:i havent understood your question

The line int[] zeroArray = new int[10]; will create an int array of size 10 and initialise all elements to zero. That's the default behaviour in Java.
for(int i = 0; i < arrayBonus.length; i++) { arrayBonus[i]++; } will solve your second problem.

Related

I need help sorting an array in java based on frequency in this one particular way

need help taking an an array, counting frequency, putting in another array with array index acting at the number and individual value acting as the frequency in Java
You can sort a large array of m integers that are in the range 1 to n by using an array count of n
entries to count the number of occurrences of each integer in the array. For example, consider
the following array A of 14 integers that are in the range from 1 to 9 (note that in this case m =
14 and n = 9):
9 2 4 8 9 4 3 2 8 1 2 7 2 5
Form an array count of 9 elements such that count[i-1] contains the number of times that i
occurs in the array to be sorted. Thus, count is
1 4 1 2 1 0 1 2 2
In particular,
count[0] = 1 since 1 occurs once in A.
count[1] = 4 since 2 occurs 4 times in A.
count[2]=1 since 3 occurs once in A.
count[3] =2 since 4 occurs 2 times in A.
Use the count array to sort the original array A. Implement this sorting algorithm in the function
public static void countingSort(int[] a, int n )
and analyze its worst case running time in terms of m (the length of array a) and n.
After calling countingSort(), a must be a sorted array (do not store sorting result in a
temporary array).
edit:
this is what i've tried
public static void countingSort1(int[] a, int n) {
int [] temp = new int[n];
int [] temp2 = new int[n];
int visited = -1;
for (int index = 0; index < n; index++) {
int count = 1;
for (int j = index +1; j < n; j++) {
if(a[index] == a[j]) {
count++;
temp[j] = visited;
}
}
if (temp[index]!= visited) {
temp[index] = count;
}
}
for(int i = 1; i < temp.length; i++) {
if (temp[i] != visited) {
System.out.println(" " +a[i] + " | " +temp[i]);
}
}
Just to count the frequency but i think im doing it wrong
Something like below should do the work:
Since you already know what the highest value is, in yor example 9,
create a frequency array with space for nine elements.
iterate over your input array and for each value you find increase
the value at the index of the value in your frequency arra by one
create a counter for the index and initialize it with 0
iterate over your frequency array in a nested loop and replace the
values in your input array with the indexes of your frequency array.
I leave the analysis of the complexity to you
public static void countingSort(int[] a, int n ){
//counting
int[] freq = new int[n];
for(int i = 0; i<a.length; i++){
freq[a[i]-1]++;
}
//sorting
int index = 0;
for(int i = 0; i< freq.length; i++){
for(int j = 0;j < freq[i];j++){
a[index++]= i+1;
}
}
System.out.println(Arrays.toString(a));
}

How to return the largest integer in an Array that has 10 random integers in it?

So this is a coding question from school I have, I don't want to say "hey guys do my homework for me!", I actually want to understand what's going on here. We just started on arrays and they kind of confuse me so I'm looking for some help.
Here's the complete question:
Write a program in which the main method creates an array with
10 slots of type int. Assign to each slot a randomly-generated
integer. Call a function, passing it the array. The called
function should RETURN the largest integer in the array to
your main method. Your main method should display the number
returned. Use a Random object to generate integers. Create it
with
Random r = new Random(7);
Generate a random integer with
x = r.nextInt();
So, here's what I have so far:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
int x = r.nextInt();
for (int i = 0; i < count.length; i++)
{
count[i] = x;
}
}
I created that array with 10 ints, then used a for loop to assign each slot that randomly generated integer.
I'm having a hard time for what to do next, though. I'm not sure what kind of method / function to create and then how to go from there to get the largest int and return it.
Any help is really appreciated because I really want to understand what's going on here. Thank you!
Here is how to generate Random ints
public static void main(String[] args) {
int []count = new int[10];
Random r = new Random(7);
int x=0;
for (int i = 0; i < count.length; i++)
{
x = r.nextInt();
count[i] = x;
}
System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number
Here is how to make method and get max number from list.
static int maxNumber(int[] mArray){//Passing int array as parameter
int max=mArray[0];
for(int i=0;i<mArray.length;i++){
if(max<mArray[i]){//Calculating max Number
max=mArray[i];
}
}
return max;//Return Max Number.
}
Ask if anything is not clear.
This is how we make method which return int.
You can do it by using a simple for loop for the Array.
First you have to create a seperate int variable (eg: int a) and assign value zero (0) and at each of the iterations of your loop you have to compare the array item with the variable a. Just like this
a < count[i]
and if it's true you have to assign the count[i] value to the variable a . And this loop will continue until the Array's last index and you will have your largest number in the a variabe. so simply SYSOUT the a variable
Important: I didn't post the code here because I want you to understand the concept because If you understand it then you can solve any of these problems in future by your self .
Hope this helps
What you have got so far is almost correct, but you currently are using the same random number in each iteration of your for-loop. Even though you need to get a new random number for each iteration of your for-loop. This is due to how the Random object is defined. You can achieve this by changing your code the following way:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
for (int i = 0; i < count.length; i++)
{
int x = r.nextInt(); // You need to generate a new random variable each time
count[i] = x;
}
}
Note that this code is not optimal but it is the smallest change from the code you already have.
To get the largest number from the array, you will need to write another for-loop and then compare each value in the array to the largest value so far. You could do this the following way:
int largest = 0; // Assuming all values in the array are positive.
for (int i = 0; i < count.length; i++)
{
if(largest < count[i]) { // Compare whether the current value is larger than the largest value so far
largest = count[i]; // The current value is larger than any value we have seen so far,
// we therefore set our largest variable to the largest value in the array (that we currently know of)
}
}
Of course this is also not optimal and both things could be done in the same for-loop. But this should be easier to understand.
Your code should be something like this. read the comments to understand it
public class Assignment {
public static int findMax(int[] arr) { // Defiine a function to find the largest integer in the array
int max = arr[0]; // Assume first element is the largest element in the array
for (int counter = 1; counter < arr.length; counter++) // Iterate through the array
{
if (arr[counter] > max) // if element is larger than my previous found max
{
max = arr[counter]; // then save the element as max
}
}
return max; // return the maximum value at the end of the array
}
public static void main(String[] args) {
int numberofslots =10;
int[] myIntArray = new int[numberofslots]; // creates an array with 10 slots of type int
Random r = new Random(7);
for (int i = 0; i < myIntArray.length; i++) // Iterate through the array 10 times
{
int x = r.nextInt();
myIntArray[i] = x; // Generate random number and add it as the i th element of the array.
}
int result = findMax(myIntArray); // calling the function for finding the largest value
System.out.println(result); // display the largest value
}
}
Hope you could understand the code by reading comments..
This can be done in one simple for loop no need to have 2 loops
public static void main(String[] args) {
Integer[] randomArray = new Integer[10];
randomArray[0] = (int)(Math.random()*100);
int largestNum = randomArray[0];
for(int i=1; i<10 ;i++){
randomArray[i] = (int)(Math.random()*100);
if(randomArray[i]>largestNum){
largestNum = randomArray[i];
}
}
System.out.println(Arrays.asList(randomArray));
System.out.println("Largest Number :: "+largestNum);
}
Initialize max value as array's first value. Then iterate array using a for loop and check array current value with max value.
OR you can sort the array and return. Good luck!
Here's a basic method that does the same task you wish to accomplish. Left it out of the main method so there was still some challenge left :)
public int largestValue(){
int largestNum;
int[] nums = new int[10];
for (int n = 0; n < nums.length; n++){
int x = (int) (Math.random() * 7);
nums[n] = x;
largestNum = nums[0];
if (largestNum < nums[n]){
largestNum = nums[n];
}
}
return largestNum;
}

Twin array Find a Minimum value from each Array index must be different

You are given two arrays A and B each containing n, integers. You need to choose exactly one number from A and exactly one number from B such that the index of the two chosen numbers is not same and the sum of the 2 chosen values is minimum.
Your objective is to find and print this minimum value.
For example in the image shown below is the minimum sum.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int twinArrays(int[] ar1, int[] ar2){
// Complete this function
int minAr1 = ar1[0];
int minAr2;
int index = 0;
for(int i =0; i<ar1.length;i++) {
if(ar1[i]<minAr1) {
minAr1 = ar1[i];
index = i;
}
}
if(index == 0) {
minAr2 = ar2[1];
}else {
minAr2 =ar2[0];
}
for(int j=0;j<ar2.length;j++) {
if(j!=index && minAr2>ar2[j]) {
minAr2 =ar2[j];
}
}
return minAr1+minAr2;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if(n>=2 && n<=1000000) {
int[] ar1 = new int[n];
for(int ar1_i = 0; ar1_i < n; ar1_i++){
int temp1 = in.nextInt();
if(temp1>=1&&temp1<=1000000) {
ar1[ar1_i] = temp1;
}
}
int[] ar2 = new int[n];
for(int ar2_i = 0; ar2_i < n; ar2_i++){
int temp2 = in.nextInt();
if(temp2>=1&&temp2<=1000000) {
ar2[ar2_i] = temp2;
}
}
int result = twinArrays(ar1, ar2);
System.out.println(result);
}
}
}
i have Implemented that is working fine but still something is missing so some test case failing could anyone give me some clue and hint to optimize my code if you find any defect in this code
Your code works by finding the minimum value from the first array, then finding the minimum value from the second array that isn't at the same position of the minimum in the first array. The problem with this approach is that it isn't guaranteed to find the overall minimum sum. For example, consider these small arrays:
[0, 1], [0, 100]
Here, if you take the minimum value of the first array (0) and the minimum value of the second array that isn't at the same position (100), you get the sum 100. However, the correct sum to pick is the smallest value from the second array (0) and the second-smallest value from the first array (1) for a total of 1.
One observation that's useful here is that the minimum-sum pair must be one of the following:
The sum of the smallest values from each array.
The sum of the smallest value from one array and the second-smallest value from the other.
Your solution is on the right track here, except you don't consider taking the smallest from the second array and the second smallest from the first. Try editing your code to account for that case.
One simple observation is that if minimum elements from both arrays are at different position, Sum of both elements would be an answer so after sorting answer in this case would be A[0]+B[0], but if both are at the same position, there are two possibilities for answer after sorting both the arrays.
Suppose we have two arrays A and B which are sorted in increasing order. Then there are two possible answers and the actual answer would be minimum of them.
Take minimum possible number from array A so that number would be A[0] and now find the minimum possible number from array B such that index of that element is not equal to 0 so best possible choice would be B[1]. Therefore answer in this case is A[0]+B[1].
Another possibility is that we consider minimum possible number from array B first and then go to choose a number from array A so here those numbers would be A[1] and B[0] respectively and thus answer in this case is A[1]+B[0].
Now for the final answer, we can take minimum of both these possible answers.
Final_Answer = min(A[0]+B[1],A[1]+B[0]);
If you don't want to sort the Arrays due to tight time constraint. You can just keep track of First and Second minimum element of both arrays and use it in place of A[0],A[1] in above equation respectively.
A sample code using first and second minimum,
static int twinArrays(int[] ar1, int[] ar2){
int first_minimum_ar1 = Integer.MAX_VALUE;
int second_minimum_ar1 = Integer.MAX_VALUE;
int index_ar1=-1;
int first_minimum_ar2 = Integer.MAX_VALUE;
int second_minimum_ar2 = Integer.MAX_VALUE;
int index_ar2=-1;
for(int i=0;i<ar1.length;i++)
{
int element = ar1[i];
if(first_minimum_ar1>=element)
{
second_minimum_ar1=first_minimum_ar1;
first_minimum_ar1=element;
index_ar1=i;
}
else if(second_minimum_ar1>element)
{
second_minimum_ar1=element;
}
}
for(int i=0;i<ar2.length;i++)
{
int element = ar2[i];
if(first_minimum_ar2>=element)
{
second_minimum_ar2=first_minimum_ar2;
first_minimum_ar2=element;
index_ar2=i;
}
else if(second_minimum_ar2>element)
{
second_minimum_ar2=element;
}
}
if(index_ar2!=index_ar1)
return first_minimum_ar1+first_minimum_ar2;
return Math.min(first_minimum_ar1+second_minimum_ar2,first_minimum_ar2+second_minimum_ar1);
}
What I did was, sort one array(ar1) in ascending order(take ar[0]) and the other in descending order(ar2) and then take (ar2[ar2.length-1]).
class TwinArray{
static int twinArrays(int[] ar1, int[] ar2){
Arrays.sort(ar1);
Integer[] Ar2 = new Integer[ar2.length];
for (int i=0;i<ar2.length;i++)
Ar2[i]=ar2[i];
Arrays.sort(Ar2,Collections.reverseOrder());
System.out.println(Ar2[Ar2.length-1]);
return (ar1[0]+Ar2[Ar2.length-1]);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ar1 = new int[n];
for(int ar1_i = 0; ar1_i < n; ar1_i++){
ar1[ar1_i] = in.nextInt();
}
int[] ar2 = new int[n];
for(int ar2_i = 0; ar2_i < n; ar2_i++){
ar2[ar2_i] = in.nextInt();
}
int result = twinArrays(ar1, ar2);
System.out.println(result);
}
}
This one will probably pass all of your test cases.
Runtime Complexity ~ o(n)
static int twinArrays(int[] ar1, int[] ar2){
int ar1Minimum = Integer.MAX_VALUE , ar1MinIndex = -1;
int ar1SecondMin = Integer.MAX_VALUE ;
//Get the element with minimum value and index
for(int i = 0 ; i < ar1.length ; ++i){
if(ar1Minimum > ar1[i]){
ar1Minimum = ar1[i]; ar1MinIndex = i;
}
}
//Get the second minimum
for(int i = 0 ; i < ar1.length ; ++i){
if(ar1SecondMin > ar1[i] && i!=ar1MinIndex){ // i != ar1MinIndex = Important to avoid duplicate minimum values [1,1,2,4] min = 1 , secondMin = 2 and not 1
ar1SecondMin = ar1[i];
}
}
int ar2Minimum = Integer.MAX_VALUE , ar2MinIndex = -1;
int ar2SecondMin = Integer.MAX_VALUE ;
for(int i = 0 ; i < ar2.length ; ++i){
if(ar2Minimum > ar2[i]){
ar2Minimum = ar2[i]; ar2MinIndex = i;
}
}
for(int i = 0 ; i < ar2.length ; ++i){
if(ar2SecondMin > ar2[i] && i != ar2MinIndex){
ar2SecondMin = ar2[i];
}
}
if(ar1MinIndex != ar2MinIndex){
return ar1Minimum + ar2Minimum;
}
return Math.max((ar1Minimum + ar2SecondMin), (ar1SecondMin + ar2Minimum));
}

Printing array elements at random until all elements have been printed

I'm trying to create a method that takes in 3 int arrays and prints out one element from each array until all the elements of all three arrays have been printed at least once. The first array has 10 elements, the second has 7, and the third has 2. The elements are selected and printed at random. Any help would be appreciated. The idea is to see how many iterations it would take to print out all the elements at least once. I don't know the conditions to set for
a large scale iteration like this. My code so far (with just one array as a parameter):
import java.util.*;
public class calculateAverage{
private static int[] x = new int[]{1,2,3,4,5,6,7,8,9,10};
private static int[] y = new int[]{1,2,3,4,5,6,7};
private static int[] z = new int[]{1,2};
public static void main(String[] args){
calculate(x);
}
public static void calculate(int a[]){
Random random = new Random();
for(int i = 0;i < a.length; i++){
System.out.print(a[random.nextInt(a.length)] + " ");
}
System.out.println();
}
}
code output:
7 2 4 1 8 10 3 10 7 3
Solution for one array:
public static int calculate(int a[]){
Random random = new Random();
HashSet<Integer> remaining = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
remaining.add(i);
}
int i = 0;
while (!remaining.isEmpty()) {
int index = random.nextInt(a.length);
System.out.print(a[index] + " ");
remaining.remove(index);
i++;
}
System.out.println();
System.out.println("Finished after " + i + " iterations.");
return i;
}
You could use a collection like Set to keep track of indexes that were already picked. Each time you generate a random number you would first check if it already exist in the Set. If not, print the value in array and add the index number to the set.
Your loop would end when size of that set equals size of the array.
int a[] = {4, 6, 3, 2, 9, 1, 5};
Set<Integer> set = new TreeSet<Integer>();
int counter = 0;
Random rand = new Random();
while(set.size() != a.length){
set.add(a[rand.nextInt(a.length)]);
counter ++;
}
System.out.println("Total Iterations : "+counter);
return counter;

Array Outofbounds exception

im getting a out of bounds error on line 57. any help is appreciated. the program takes 1 integer and creates and array with that many indexes. it then asks for more integers to fill it up. it then takes all the even numbers and places it into a second array with is then outputted.
run:
Enter the ammount of integers you will require.
10
Enter your integers:
1
Enter your integers:
2
Enter your integers:
3
Enter your integers:
4
Enter your integers:
5
Enter your integers:
6
Enter your integers:
7
Enter your integers:
8
Enter your integers:
9
Enter your integers:
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at AllEven.arrcheck2(AllEven.java:57)
at AllEven.main(AllEven.java:24)
Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)
CODE
import java.util.*;
public class AllEven {
public static void main(String[] args) {
int read;
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the ammount of integers you will require.");
read = kybd.nextInt();
int[] arr1 = new int[read];
int[] arr2;
int count = 0;
arrRead(arr1);
arrcheck(arr1);
arr2 = new int[count];
arrcheck2(arr1, arr2);
mainPrint(arr2);
}
public static int arrcheck(int[] arr1) {
int count = 0;
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] % 2 == 0) {
count++;
}
}
return count;
}
public static void arrRead(int[] arr1) {
Scanner kybd = new Scanner(System.in);
for (int i = 0; i < arr1.length; i++) {
System.out.println("Enter your integers: ");
arr1[i] = kybd.nextInt();
}
}
public static void arrcheck2(int[] arr1, int[] arr2) {
int j = 0;
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] % 2 == 0) {
arr2[j] = arr1[i];
j++;
}
}
}
public static void mainPrint(int[] arr2) {
for (int i = 0; i < arr2.length; i++) {
System.out.println("Printing Even Numbers.");
System.out.println(arr2[i]);
}
}
}
ok so thanks everyone who helped, But now after the integers have been inputted the program just finishes without displaying anything after.
You need to assign the return value of arrcheck invocation in count variable before creating arr2. Otherwise, you would create your arr2 with size 0.
Change: -
int count = 0;
arrRead(arr1);
arrcheck(arr1);
to: -
arrRead(arr1);
int count = arrcheck(arr1);
After brief look at the code I think your problem lies here:
int count = 0;
arrRead(arr1);
arrcheck(arr1);
arr2 = new int[count]; //array of size 0!
arrcheck2(arr1, arr2);
You are defining arr2 as a zero-length array:
int count = 0;
....
arr2 = new int[count];
Then, in arrcheck2 you have the line:
arr2[j] = arr1[i];
This will not work because arr2 has no length so you cannot put anything into it.
The size of arr2 is 0. so when you try to access a non existing index in it you get the exception.
You create an array with length 0.
arr2 = new int[count];
You should give it a length bigger than 0.
If you want it to be the same length as arr1 just do arr2 = new int[read];
You need to initialize arr2 to the same length as arr1. int count = read will fix the issue. Or you can remove count entirely and just use read when initializing the array.
read = kybd.nextInt();
int[] arr1 = new int[read];
int[] arr2;
int count = read;
arrRead(arr1);
arrcheck(arr1);
arr2 = new int[count];
For starters you have your arrcheck function returning a count and not doing anything with it. I suspect you meant to write something like this:
arrRead(arr1);
int count = arrcheck(arr1);
otherwise your next line:
arr2 = new int[count];
creates an array of size 0 which will cause array out of bounds as soon as it is accessed.
Also you spelled Amount wrong, I think the rest of the program should work with the above change.
You are not initializing your array int[] arr2. You should not use an array to populate even elements from the initial array because arrays require a determined size upon initialization -- you are better off using ArrayList and then conver it into an array once you know the definitive size, if you must.

Categories

Resources