dealing with arrays containing temperature of the year - java

i have an array of length 360 this array holds the temperature of every day in the year I am asked to write a method which calculate and prints the average of temperature in each month taking into consideration that each month is made of 30 days. this is my code till naw
public static void displayAvgTemp(int[] temp){
int sum = 0;
for(int i = 0; i < temp.length; i++){
if(i / 30 != 0){
for(int j = i; i < temp.length; i++)
sum += temp[i];
}
}
}

public static void displayAvgTemp(int[] temp) {
//its a problem that temp[] starts from index 0
//so I shift elements with 1 to right, so I can iterate starting from index 1
int[] tempShifted = new int[temp.length+1];
System.arraycopy(temp, 0, tempShifted, 1, temp.length);
float sum = 0;
for (int i = 1; i < tempShifted.length; i++) {
sum += tempShifted[i];
if (i % 30 == 0) {
System.out.println(sum / 30);
sum = 0;
}
}
}

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

How to get indices as well as array numbers printed out horizontally?

I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}

Java lottery game : finding a sequence in an array

How do I see if the first 2, 3, 4 or all numbers are part of another array?Here "lottery" generates 10 numbers 1-100 and "numbers" is getting user's input 5 times.The program compares user's 5 numbers to numbers 1-5 of lottery , 2-6 and so on.Im trying to see if the user guessed a sequence in the lottery array but I cant get it to print out "You guessed 2 nrs" if the user guessed 2 ,3 ,4 or all numbers one after another.I incremented a counter and also tried switch statements but doesn't work.
// to check if user guessed a sequence
int counter=0;
for (int i = 0; i < lottery.length - 5; i++) { // 1-5
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 1; i < lottery.length - 4 ; i++) { // 2-6
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 2; i < lottery.length - 3 ; i++) { // 3 -7 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 3; i < lottery.length - 2; i++) { // 4 - 8 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 4; i < lottery.length - 1; i++) { // 5 -9 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 5; i < lottery.length ; i++) { // 6 -10 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 0; i < numbers.length && i < 2; i++) { // 2 sequence
counter = numbers[i];
}
for (int i = 0; i < numbers.length && i < 3; i++) { // 3 sequence
counter= numbers[i];
}
for (int i =0; i < numbers.length && i < 4; i++) { // 4 sequence
counter = numbers[i];
}
for (int i = 0; i < numbers.length; i++) { // 5 sequence
counter = numbers[i];
}
switch (counter) {
case 1:
System.out.println("You guessed one sequence");
break;
case 2:
System.out.println("You guessed two sequences");
break;
case 3:
System.out.println("You guessed three sequences");
break;
case 4:
System.out.println("You guessed four sequences");
break;
}
Your code is a little bit confusing, most likely because you are not using functions, for what you want to achieve there is a nice code here, lets take a look at it:
static boolean isSubArray(int A[], int B[], int n, int m)
{
// Two pointers to traverse the arrays
int i = 0, j = 0;
// Traverse both arrays simultaneously
while (i < n && j < m)
{
// If element matches
// increment both pointers
if (A[i] == B[j])
{
i++;
j++;
// If array B is completely
// traversed
if (j == m)
return true;
}
// If not,
// increment i and reset j
else
{
i = i - j + 1;
j = 0;
}
}
return false;
}
Now you have a function that will return true if whole sequence A is in sequence B, but that is not the whole code you seem to want. You need to split guessed sequence, what if there is subsequence that fits?
Example (how many are guessed in following?):
int lottery[] = {1,2,3,4,5,6,7,8,9,10};
int A[] = {1,2,3,4,5}; //here we got full match
int B[] = {1,2,4,5,6}; //last three make it 3
int C[] = {1,2,3,7,9}; //first three make it 3
int D[] = {1,3,4,5,9}; //and here is it in the middle!
So what now? You need to check for each lengths, higher lengths first of course, a simple solution can be as follows (check how to create a subarray):
import java.util.Arrays;
public static<T> T[] subArray(T[] array, int beg, int end) {
return Arrays.copyOfRange(array, beg, end + 1);
}
public static boolean checkAll(int A[], int B[], int n, int m, int subset){
for(int i=0;i+subset<n;i++){ //i+subset must be within range
//checking the current subset, iterate them all
if(isSubArray(subArray(A,i,i+subset), B, n, m)){
return true; //if it is there return true!
}
}
return false; //no luck!
}
int lottery[] = {1,2,3,4,5,6,7,8,9,10};
int D[] = {1,3,4,5,9};
counter = 0;
for(counter=D.length; counter>0; counter--){
if(checkAll(D, lottery, D.length, lottery.length, counter)){
break; //we found match, can end
}
}
System.out.println("You guessed sequence of length: %d ", counter);
I guess I have a little bit misunderstood what you are trying to achieve, so same approach for sequences of the lottery:
//subset is probably 5 for lottery
public static int checkAll(int A[], int B[], int n, int m, int subset_A , int subset_B){
int total = 0;//we return this
for(int i=0;i+subset_B<m;i++){ //each subset in lottery
for(int j=0;j+subset_A<n;j++){ //each subset in guesses
if(isSubArray(subArray(A,j,j+subset),subArray(B,i,i+subset), n, m)){
total++;
}
}
return total;
}
int occurences = 0;
for(int counter=lottery.length; counter>0; counter--){
occurences+=checkAll(D, lottery, D.length, lottery.length, counter, 5);
}
System.out.println("Your guessed sequence (and its parts) was present %d times", occurences );
I am still not sure what exactly you want to do, so this code might be a little bit overkill. The code was not tested, some syntax errors might come in the way.

How can I sum the product of two two-dimensional arrays?

So I got a code with two arrays: one array contains tickets sold for three cinemas and the other one contains the adult and kid prices. My code outputs the total for every cinema separately (3 lines of output) but I need the total number of those 3. So instead of printing 828 for cinema1, 644 for cinema2, 1220 for cinema3 and I need it to print 2692 (total of 3 cinemas). How can I sum the 3 products with a for loop? Here's the code:
public class Arrays {
public Arrays() {}
public static void main(String[] args) {
float[][] a = new float[][] {{29, 149}, {59, 43}, {147, 11}};
float[] b = new float[] {8, 4};
String[] s = new String[] {"cinema 1", "cinema 2", "cinema 3"};
String[] t = new String[] {"Adults", "Children"};
int i,j;
System.out.println("Cinema Complex Revenue\n\n");
for ( i = 0 ; i <= 2 ; i++ )
{
for ( j = 0 ; j < 1 ; j++ )
{
System.out.println(s[i] + "\t$" +
(a[i][j] * b[j] + a[i][j + 1] * b[j + 1]));
}
}
}
}
And the output: 1
Just code what you want.
int i, j;
float sum = 0;
for (i = 0; i < a.length; i++) {
for (j = 0; j < a[i].length && j < b.length; j++) {
sum += a[i][j] * b[j];
}
}
System.out.println(sum);
Or if you want to use only one for loop, it may be
int i;
float sum = 0;
for (i = 0; i < a.length * b.length; i++) {
sum += a[i / b.length][i % b.length] * b[i % b.length];
}
System.out.println(sum);
All you need is 1 nested for-loop:
Integer totalCost = 0;
for( i = 0 ; i<b.length; i++ ) {
//you should check if the a[i].length == b.length, and throw an exception if not!
for( j = 0 ; j<a.length; j++) {
totalCost += b[i]*a[j][i];
}
}
System.out.println("Total cost: "+totalCost.toString());

Counting occurrences of integers in an array in Java

Note: no mapping, no sorting
Here's my code:
public static void countArray(int[] n){
int[] m = new int[n.length]; //50 elements of integers between values of 10 & 20
int count = 0;
int sum = 0;
for ( int i = 0; i < n.length ; i++){
m[i] = n[i]; //make a copy of array 'n'
System.out.print(m[i]+" ");
}System.out.println();
for ( int j =0; j < n.length ; j++){
count =0;
for(int i = 0; i < n.length ; i++){
if (n[j]%m[i]==0 && n[j] == m[i])
count++;
}if ( n[j]%m[j] == 0)
System.out.println(m[j] + " occurs = " + count);
}
}
So the problem is: I get repeating results like : "25 occurs = 5", on different lines.
What I think: the problem occurs because of if ( n[j]%m[j] == 0)
so I tried if ( n[j]%m[j+1] == 0). Another problem occurs since m[j] will be m[50] so it crashes but sort of give me the results that I want.
Result that I want: something like this: no repetitions and covers all the random integers on a set
17 occurs = 3
23 occurs = 2
19 occurs = 3
15 occurs = 2
12 occurs = 2
With some adaptation your code should work :
public static void countArray(int[] n){
boolean [] alreadyCounted = new boolean[n.length];
for (int i = 0; i < n.length ; i++){
int count = 0;
if (alreadyCounted[i]) {
// skip this one, already counted
continue;
}
for(int j = 0; j < n.length ; j++){
if (n[i] == n[j]) {
// mark as already counted
alreadyCounted[j] = true;
count++;
}
}
System.out.println(n[i] + " occurs = " + count);
}
}
You could definitely use the same logic with better code, I just tried to follow the original "coding style";
This is O(n^2) solution (read "very slow").
If you could use sorting, you could do it in O(n log(n)) - that is fast.
With mapping you could do it in O(n) - that is blazingly fast;
If you exploit the input limit you can lose the nested loop:
public static void main(String[] args)
{
//6 elements of integers between values of 10 & 20
int[] countMe = { 10, 10, 20, 10, 20, 15 };
countArray(countMe);
}
/** Count integers between values of 10 & 20 (inclusive) */
public static void countArray(int[] input)
{
final int LOWEST = 10;
final int HIGHEST = 20;
//Will allow indexes from 0 to 20 but only using 10 to 20
int[] count = new int[HIGHEST + 1];
for(int i = 0; i < input.length; i++)
{
//Complain properly if given bad input
if (input[i] < LOWEST || HIGHEST < input[i])
{
throw new IllegalArgumentException("All integers must be between " +
LOWEST + " and " + HIGHEST + ", inclusive");
}
//count
int numberFound = input[i];
count[numberFound] += 1;
}
for(int i = LOWEST; i <= HIGHEST; i++)
{
if (count[i] != 0)
{
System.out.println(i + " occurs = " + count[i]);
}
}
}
try this :(sort the array and then count the occurence of element)
public static void countArray(int[] n) {
int count = 0;
int i, j, t;
for (i = 0; i < n.length - 1; i++) // sort the array
{
for (j = i + 1; j < n.length; j++) {
if (n[i] > n[j]) {
t = n[i];
n[i] = n[j];
n[j] = t;
}
}
}
for (i = 0; i < n.length;)
{
for (j = i; j < n.length; j++) {
if (n[i] == n[j])
{
count++;
} else
break;
}
System.out.println(n[i] + " occurs " + count);
count = 0;
i = j;
}
}
Here's a nice, efficient way to do it, rather more efficiently than the other solutions posted here. This one runs in O(n) time, where the array is of length n. It assumes that you have some number MAX_VAL, representing the maximum value that you might find in your array, and that the minimum is 0. In your commenting you suggest that MAX_VAL==20.
public static void countOccurrences(int[] arr) {
int[] counts = new int[MAX_VAL+1];
//first we work out the count for each one
for (int i: arr)
counts[i]++;
//now we print the results
for (int i: arr)
if (counts[i]>0) {
System.out.println(i+" occurs "+counts[i]+" times");
//now set this count to zero so we won't get duplicates
counts[i]=0;
}
}
It first loops through the array increasing the relevant counter each time it finds an element. Then it goes back through, and prints out the count for each one. But, crucially, each time it prints the count for an integer, it resets that one's count to 0, so that it won't get printed again.
If you don't like the for (int i: arr) style, this is exactly equivalent:
public static void countOccurrences(int[] arr) {
int[] counts = new int[MAX_VAL+1];
//first we work out the count for each one
for (int i=0; i<arr.length; i++)
counts[arr[i]]++;
//now we print the results
for (int i=0; i<arr.length; i++)
if (counts[arr[i]]>0) {
System.out.println(arr[i]+" occurs "+counts[arr[i]]+" times");
//now set this count to zero so we won't get duplicates
counts[arr[i]]=0;
}
}

Categories

Resources