Computing the frequency of 5 in an array - arrays

Very basic query here from a beginner...
I'm looking to find the frequency of a number within an array...
In the (mangled) code below I have tried to calculate the occurances of the number 5 in the array
I'm running into problem in formulating the for loop
Heres my code attempt:
//Compute the frequency of 5 in the array named numbers
public class find //Begin class
{
public static void main (String []args) //Begin main
{
double numbers[] = {6,7,12,5,4,2,4,6,9,5,7,11,1,23,32,45,5}; //Initialise and populate array
int total = 0;
int counter = 0;
for (int x : numbers)
{
if (numbers[] == 5; counter ++)
{System.out.println( numbers[i] + " ");
}
}
// end code
// *****************

int numbers[] = {6,7,12,5,4,2,4,6,9,5,7,11,1,23,32,45,5};
for(int x : numbers) {
if(x == 5)
counter++;
}
System.out.println(counter);
I can see that you were trying to use a for each loop in your implementation.
#Code Whisperer provides a good alternative to that, but if you do want to use a for each loop then you have to make sure you loop type and array type match. In your case, your array is type double but your loop type is int. Within each iteration, you're selecting an individual value in the array, so you don't need to include any brackets.

for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == 5) {
counter++;
System.out.println(counter); // shows how many 5s you have so far
}
}
Loop through array, compare every element in the array to 5. If it is 5, increment counter by 1.

Related

Trying to create a minesweeper like game placing random mines with user input using 2d array

Im trying to create a minesweeper like simulation when 0 is clear and X is a mine the user inputs the number of mines and using a random generator places it in the 2D array. When i run it the grid print but i get java.lang.ArrayIndexOutOfBoundsException: 4 and not sure how to fix it. I have never worked with 2D arrays before.
import java.util.Scanner;
import java.util.Random;
public class Minesweeper {
private static int count = 0; /* used to count the number of mines */
public static void main ( String [] args) {
int r = 12;
int c = 12;
int ground [][] = new int [r][c]; //2D array 12 x 12
int a = 0; // variable to print 0's as an integer instead of a string
Scanner sc=new Scanner(System.in); // scanner for the user to input number of mines
System.out.print("Enter mines: ");
Random myRandom = new Random();
int N; // N is the variable for the number of mines
N = sc.nextInt(); // scanner to input the number
for (int k = 0; k < ground.length; k++) { // nested loop to print a 12 x 12 grid
for (int j = 0; j < ground.length; j++) {
System.out.print(" " + a + " " ); // prints the 0s
}
System.out.println();
}
while(count <= N) { // loop to count the mine numbers the user chose
/* if count < N, we need to put more mines */
do {
r = myRandom.nextInt(12); // generate the mines in random places
c = myRandom.nextInt(12);
} while(mineOrNot(r, c) == false);
count += 1;// count to place the right amount of mines
}
}
// function to make sure no 2 mines are in the same location
public static boolean mineOrNot(int r, int c) {
int ground [][] = new int [r][c];
// if theres no mines its ok to place one
if(ground[r][c] == 0) {
ground[r][c] = 1; // it is ok, put a mine at here
return true;
}
else
return false;
}
}
Since I don't code in Java, I can only give you the basics of why you're receiving this error. It's basically a right of passage for starting out with arrays, and even experienced programmers run into this issue from time to time in certain cases.
Array Indexing in Java
Basically, what's happening is you're attempting to access a part of this array that does not exist within the range you've set for it.
E.G. You're accessing element 13, null, and attempting to use it, causing the error.
Throw a breakpoint in if you can (don't use Java, I imagine Oracle has this functionality) and step through each iteration and try and count exactly the ticks over your array.
It should remain from 0 - 11, since array indexes in Java start at 0.
So your 1 - 12 cells become index
0 - 11.

Occurence of a element in unsorted array by O(n)

This is driving me nuts:(
Problem statement:
An unsorted array is inputed.Next the user gives a collection of numbers and the program should print the occurrence of the given number in that array.
This should run at O(n) time complexicity.
Example:
Input array:[1, 1, 1, 2, 2, 0]
Collection of numbers:
1
2
1
0
Output:
3
2
3
1
Constrains:Array can be of size 10^5 and collection of number can be of size 10^5
P.S:I have made a code with O(n^2)
#include<stdio.h>
#include<stdlib.h>
void main(){
int *n,size,key,count=0;
scanf("%d",&size);
n=(int*)malloc(size*sizeof(int));
for(int i=0;i<size;i++){
scanf("%d",&n[i]);
}
scanf("%d",&key);
for(int i=0;i<key;i++){
count=0;
int temp=0;
scanf("%d",&temp);
for(int j=0;j<size;j++){
if(temp==n[j])
count+=1;
}
printf("\n");
if(count==0){
printf("NOT PRESENT");
}
else{
printf("%d",count);
}
}
}
Any help is welcomed :)
The range of elements is small. So create an array of counters for the possible values and increment the count for each value you find. For example, if you find 2, increment counter[2].
Then given your collection of numbers, just do an array lookup to get the count.
The time complexity is O(max(m,n)) where m is the size of the array and n is the size of the collection. The space required is O(p) where p is the range of the integers that may appear in the array. We'll use p0 to denote the lower bound of this range.
The solution is simple:
Construct an array C of size p and set all values to zero
Walk over the input array and for each value k - increase C[k-p0] by 1. Now you have a count of each value.
Walk over the collection and for each value k - print C[k-p0]
You can simply make a array of 10^5 and initialize it with 0. Now iterate over array and increment the value in array. Like you encounter a 5 increment arr[5] and now you can answer the queries in O(1) time.
Below is a code in java.
import java.util.Scanner;
public class test
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in());
int n=s.nextInt();
int arr[]=new int[100001]; //Array is initialized 0
for(int i=0;i<n;i++)
{
int num=s.nextInt();
arr[num]++;
}
while(s.hasnextInt())
{
int p=s.nextInt();
System.out.println(arr[p]);
}
}
}
A very simple way to do this would be to have your resulting array's keys be where the values are.
My C skills are kind of weak, but here is how in pseudo-C (you'll have to tweak it to make it work properly:
int size = 10*10*10*10*10;
int[size] input = getInput();
int[size] results = new int[size](0); // fill array with zeros
for(int i = 0; i < size; i++) {
if (input[i] === -1)
break; // assuming -1 signifies the end of the input
output[input[i]]++; // increment the value at the index that matches the number by one
}
for(int i = 0; i < size; i++) {
if (output[i] === 0)
continue; // number wasn't in array
printf('%d', output[i]);
}
Basically, you put the input of the array in the matching index of output.
So, if your input is 5,3,2,1,1,5,3,2,1, you would put into output:
output[5]++;
output[3]++;
output[2]++;
output[1]++;
output[1]++;
output[5]++;
output[3]++;
output[2]++;
output[1]++;
resulting in an array that looks like this:
[0, 3, 2, 2, 0, 1]
Then you just output it, skipping the zeros because they weren't present.

Randomly select index of matrix exactly once

I have a matrix of 1's (just a 2D vector of ints) and I am trying to randomly select an index so that I can turn that 1 to a 0. My goal is to select every index of the matrix exactly once so that after running a for loop with exactly as many iterations as there are indices, the matrix will be filled with 0s (the 0 doesn't actually matter, the number that replaces the 1 and the 1 itself are arbitrary).
My current approach is very slow. It has been to run a while loop that checks each pass to see if there are still any 1's left. This is obviously incredibly inefficient, but I am not sure how to do this only once for each index and ensure there are no repeats so that I can change to a for loop. Any advice would be very helpful!
Just generate a random sequence of the matrix indices as #Jonny mentioned in the comment. Then iterate through each element of this sequence. The following is a Java implementation I just wrote in case it helps:
import java.util.Random;
public class Test {
public static void randomSelectMatrixIndex(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int[] indices = new int[rows*cols];
System.out.println("Index array before shuffle: ");
for (int i=0; i<indices.length; i++) {
indices[i] = i;
System.out.print(i+" ");
}
System.out.println();
System.out.println();
shuffle(indices);
System.out.println("Index array after shuffle: ");
for (int j=0; j<indices.length; j++) {
System.out.print(indices[j]+" ");
matrix[indices[j]/cols][indices[j]%cols] = 0;
}
System.out.println();
System.out.println();
}
private static void shuffle(int[] indices) {
Random ran = new Random();
for (int i=indices.length; i>0; i--) {
int randomIndex = ran.nextInt(i);
int temp = indices[i-1];
indices[i-1] = indices[randomIndex];
indices[randomIndex] = temp;
}
}
private static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) throws Exception {
int[][] matrix = {{1,1,1,1,1}, {1,1,1,1,1}, {1,1,1,1,1}, {1,1,1,1,1}};
System.out.println("Matrix before random select: ");
printMatrix(matrix);
System.out.println();
randomSelectMatrixIndex(matrix);
System.out.println("Matrix after random select: ");
printMatrix(matrix);
}
}
You use this algorithm, which is a bit more efficient, although still not very efficient after a lot of iterations (note that for best result, use a evenly distributed random number generator):
select random index -> check if 1
| | |
| repeat |False |True
|--------------------| |--Change value at index to 0
|
|
the end
I wonder if there is something one could change to make it more efficient...
Simple. Create a vector of pointers using nested loops so that there's a pointer to every single element in the matrix. Randomly select a pointer. Change value to 0. Remove pointer from vector. Repeat until vector is empty. Matrix is now empty.

Calculating the dispersion in C

I'm trying to calculate the dispersion between two values, one I get from and certain parameter('age') from each entry on the array of structures.
I've got an auxiliary .txt file and, the whole point of this is to go through each of the lines of the .txt file individually (each line is a string). It's better if I state an example, so, here we go:
matrix[n][n]:
1 2 3 4
1 2 3
1 2
So, the structure would look a bit like this:
struct person {
int id; //where im comparing between the matrix and the structure;
int age; //what I need to calculate the dispersion
}
I gotta compare the each value of each line of the .txt, and if it matches any of the id's on the structure, I gotta get its age. Now comes the tricky part.
To calculate the dispersion I need to get the following working out for me:
Let's take as example the first row of the .txt file: the dispersion would be:
let's say that 'age' = age of the id (n);
//in this case nGroups = 6 (number of age(n)-age(m) operations)
dispersion(first_row)= [ [|age(1)-age(2)|] + [|age(1)-age(3)|] + [|age(1)-age(4)|] + [|age(2)-age(3)|] + [|age(2)-age(4)|] + [|age(3)-age(4)|] ]/nGroups
So I have to do this for each row of the matrix. I've tried it and managed the following code, but in the 'math' part my brain freezes a bit.
// going through each line of the matrix
for(i=0; i<nconjuntos; i++) {
// going through each column of the matrix
for(j=0; j<strlen(aux[i]); j++) {
// going through all the structures in the structure array
for(k=0; k<TOTAL; k++) {
// comparing each number with it's id equivalent in
// each structure.id parameter in the array
if(aux[i][j] - 48 == pessoas[k].id) {
}
}
}
}
Any help that would help me to advance in my code would be really appreciated!
You have two problems here requiring a solution:
Match the id in the matrix with the id in the structure and get a list of ages for a given row
Calculate the dispersion
It's probably easiest if you separate these two tasks instead of doing them both inside the same nested for loop. You can write a function to calculate the dispersion according to the formula you gave like this:
double calculateDispersion(double* values, int count)
{
if(count < 2)
return 0.0; // need at least 2 values
double total = 0.0;
// iterate through each combination of values and sum the absolute
// differences of each combination:
int i, j;
for(i = 0; i < (count - 1); i++)
{
for(j = i + 1; j < count; j++)
{
double difference = values[i] - values[j];
if(difference < 0.0) // find absolute value
difference = 0.0 - difference;
total += difference; // add to the total
}
}
int groups = (count * (count - 1)) / 2;
return total / (double)groups;
}
Inside your main loop create an array of doubles equal in size to the largest row in your matrix, to store the ages for the current row (or floats, but using ints will give you rounding errors). Fill it up by cross-referencing with the structs containing the id and age. Then call calculateDispersion() to calculate the dispersion for the row.
Something like roughly this:
double rowArray[MAX_SIZE]; // or initialize to maximum matrix row length dynamically
// going through each line of the matrix
for(i=0; i<nconjuntos; i++) {
int count = 0;
// going through each column of the matrix
for(j=0; j<strlen(aux[i]); j++) {
// going through all the structures in the structure array
for(k=0; k<TOTAL; k++) {
// comparing each number with it's id equivalent in
// each structure.id parameter in the array
if(aux[i][j] - 48 == pessoas[k].id) {
// set array value:
rowArray[count++] = (double)pessoas[k].age;
break; // break out of the loop
}
}
}
// compute the dispersion for the row:
doubleDispersion = calculateDispersion(rowArray, count);
}

How to count how many times values were used in the array C?

Here's my problem
If certain number has been entered into an array I need that number to be displayed and occurrence of that number in the array.
for example if user enters number 5 three times then "The number 5 has been entered 3 times so far" and so on
Here's my code so far:
int i,j;
int num_count = 0;
for(i=0;i<6;i++) {
num_count = 0;
for(j=1;j<43;j++) {
if( *(num + i) == j) {
printf("The number %d has been used %d times\n",j,num_count);
}//end if
}//end inner for
}//end outer for
I will like to suggest you a very time efficient method for this, but it needs some extra memory.
Assume the upper limit of numbers inside array is 'MAX_NUM_IN_ARRAY',
so you should create array (say counter) of size 'MAX_NUM_IN_ARRAY+1' and initialize it to 0.
int counter[MAX_NUM_IN_ARRAY+1]={0};
now scan the input array from first to last element,
for each number:
//say number is num
counter[num]++;
and at the end you have to just scan that counter array from index 1 to MAX_NUM_IN_ARRAY.
Sample code:
Suppose input array is a[],
number of elements in array is n,
maximum limit of number inside array is MAX_LIMIT
int counter[MAX_LIMIT]={0};
int i;
for(i=0; i<n; i++)
{
counter[a[i]]++;
}
for(i=0; i<MAX_LIMIT; i++)
{
printf("Number %d is appeared for %d times\n", i, counter[i]);
}
============EDIT
You could write a series of functions that handle your collection. the collection could be a 2 dimentional array like so numbers[][] where numbers[n][0] is your number, and numbers[n][1] is the number of times it occurred... and the gold would be in your add() function
add() does a few things, a user passes a value to add(),
first checks if number exists in numbers[n][0]
if the value exists at numbers[n][0]
numbers[n][1]++;
if it doesn't already exist,
check if the array is full
if it is full, copy all the data to a new, larger array
add it to the end of the array.. this is how to do it.
==OR
just design a 1 dimentional array numbers[] that holds all of your numbers.. and the add() function only:
if(it is full){copies to larger array}
adds number to the end;
and modify the code I wrote earlier (Below).. to print the most common number and it's occurrence count
============EDIT
I'm a Java guy so you'll need to translate (shouldn't be too hard..)
This is going to be just like a sorting algorithm with a little bit of extra logic (later search for Selection Sort)
int[] temp = {4,3,2,4,4,5};
////// find the most commonly occuring value
int times;
int moreTimes = 1;
int value = temp[0];
for(int i = 0; i < temp.length; i++) {
times = 1;
for(int j = i+1; j < temp.length; j++) {
if(temp[i] == temp[j])
times++;
}
if(times > moreTimes) {
moreTimes = times;
value = temp[i];
}
}
/////// count the most common value
int count = 0;
for(int i = 0; i < temp.length; i++) {
if(temp[i] == value)
count++;
}
System.out.println("number: " + value + ", count: " + count);

Resources