I was reading about arrays in java and I made a code for calculating the number of appearances of all numbers in an array .
public class Example {
static int b[] = new int[13]; // I can not do static int b[] = new int[a.length] because a[] in not static array
static int count = 0;
public static void main(String[] args) {
int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 };
counting(a);
printCount();
}
private static void printCount() {
int k = 0;
for (int i = 0; i < b.length; i++) {
System.out.print("number" + " " + a[k] + " " + "is found" + " "); // here I get error in a[k] because it is not static , eclipse says : a cannot be resolved to a variable
System.out.println(b[i] + " " + "times");
k++;
}
System.out.println();
}
private static void counting(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] == a[k]) {
b[i] = ++count;
}
}
count = 0;
}
}
}
I got stuck in my printCount() method , there I can not call my a[] array in the method because a[] is not static in the main method .
I tried to write static int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 }; in my main method but eclipse does not accept that .
How can I make a[] a static array so that can be reached in all methods in my Example class above ?
Thank you
public static void main(String[] args) {
int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 };
counting(a);
printCount(a);
}
Pass the array in the printCount() method.
Why do you want a[] to be static if you don't want it moved out of the main method? The only way it can be accessed outside main() is if it was passed through. No way to call Example.a[] like a normal static variable. Seems to me like you need to get the length of a[] after it is initialized, and then set the bounds for b[] all within the main method.
You can move the a array out to the class scope as static. Then for your array practicing you can easily just change the a array.
However, as others also mention I recommend you to study scopes in Java .
public class Example {
static int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 };
static int[] b = new int[a.length];
static int count = 0;
public static void main(String[] args) {
counting();
printCount();
}
private static void printCount() {
int k = 0;
for (int i = 0; i < b.length; i++) {
System.out.print("number" + " " + a[k] + " " + "is found" + " ");
System.out.println(b[i] + " " + "times");
k++;
}
System.out.println();
}
private static void counting() {
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] == a[k]) {
b[i] = ++count;
}
}
count = 0;
}
}
}
Related
This code is about algorithms and datastructures. This code runs perfectly and i just have some questions on it because it seems like i don't understand two points. So my questions for that is:
which informations are in the countingArray?
how often is the while loop executed?
public class CountingSort {
public static void main(String[] args) {
int[] m1 = { 1, 17, 3, 1, 4, 9, 4, 4 };
System.out.println("unsorted:");
output(m1);
int min1 = rangeMin(m1);
int max1 = rangeMax(m1);
countingSort(m1, min1, max1);
System.out.println("sorted:");
output(m1);
int[] m2 = { -1, 13, 3, -1, -4, 9, -4, 4 };
System.out.println("unsorted:");
output(m2);
int min2 = rangeMin(m2);
int max2 = rangeMax(m2);
countingSort(m2, min2, max2);
System.out.println("sorted:");
output(m2);
}
public static void output(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + ", ");
}
System.out.println();
}
public static int rangeMin(int[] a) {
int minimum = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < minimum)
minimum = a[i];
}
return minimum;
}
public static int rangeMax(int[] array) {
int maximum = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > maximum)
maximum = array[i];
}
return maximum;
}
public static void countingSort(int[] array, int rangeMin, int rangeMax) {
int[] countingArray = new int[rangeMax - rangeMin + 1];
for (int i : array) {
countingArray[i - rangeMin]++;
}
int c = 0;
for (int i = rangeMin; i <= rangeMax; i++) {
while (countingArray[i - rangeMin] > 0) {
array[c] = i;
c++;
countingArray[i - rangeMin]--;
}
}
}
}
CountingSort has O(n) time and space complexity. You iterate (i.e. use for loop) twice.
public class CountingSort {
public static void main(String... args) {
proceed(1, 17, 3, 1, 4, 9, 4, 4);
System.out.println("---");
proceed(-1, 13, 3, -1, -4, 9, -4, 4);
}
public static void proceed(int... arr) {
System.out.print("unsorted: ");
print(arr);
countingSort(arr);
System.out.print("sorted: ");
print(arr);
}
public static void print(int... arr) {
System.out.println(Arrays.stream(arr)
.mapToObj(i -> String.format("%2d", i))
.collect(Collectors.joining(",")));
}
public static void countingSort(int... arr) {
int min = Arrays.stream(arr).min().orElse(0);
int max = Arrays.stream(arr).max().orElse(0);
// contains amount of number in the unsorted array
// count[0] - amount of min numbers
// count[count.length - 1] - amount of max numbers
int[] count = new int[max - min + 1];
for (int i : arr)
count[i - min]++;
// fill source array with amount of numbers
for (int i = 0, j = 0; i < count.length; i++)
for (int k = 0; k < count[i]; k++, j++)
arr[j] = min + i;
}
}
I'm trying to compare two int arrays, where array 1 is the standard (1...n) and array 2 is random numbers within the range of (1...n). The numbers that are missing from array 2 need to be printed out. So far, I've managed the following, but I can't seem to figure out how to use the boolean array to my benefit.
import java.util.Scanner;
public class findLeaves {
private boolean[] id;
private String[] surface;
private int[] head;
public boolean[] inputId() {
System.out.println("Input number of IDs");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
id = new boolean[n];
return this.id;
}
public int[] inputHead() {
System.out.println("Input each head value.");
head = new int[id.length];
for (int i = 0; i < id.length; i++){
Scanner scan = new Scanner(System.in);
head[i] = scan.nextInt();
}
return this.head;
}
public boolean Leaves() {
for (int i = 0; i < head.length; i++);
for (int j = 0; j < id.length; j++) {
if (!id[j]) System.out.print(j + ",");
}
return true;
}
public static void main(String[] args) {
findLeaves x = new findLeaves();
x.inputId();
x.inputHead();
x.Leaves();
}
}
Currently, Leaves() is just printing out:
0,1,2,3,4,5,6,7,8,
Does anyone know of a way that this can be accomplished? I'm relatively new to Java, and haven't been able to find anything googling or here that solves my problem. Thanks in advance!
Edit:
When I update Leaves to be:
public boolean Leaves() {
for (int i = 0; i < head.length; i++) id[head[i]] = true;
for (int j = 0; j < id.length; j++) {
if (!id[j]) System.out.print(j + ",");
}
return true;
}
I get an error of:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at findLeaves.Leaves(findLeaves.java:28)
at findLeaves.main(findLeaves.java:39)
First of all, you have termination point here for (int i = 0; i < head.length; i++);, so you'll not even run this loop.
This is a shorter way to find missing value from original array in random:
import java.util.Arrays;
public class Main {
private int[] original = new int[] {1, 3, 5, 7, 9}; // original array
private int[] random = new int[] {1, 2, 3, 4, 5, 6}; // missing value from original array will be printed
public static void main(String[] args) {
Main m = new Main();
Arrays.sort(m.original); // sort is required for binarySearch()
for (int i : m.random) {
if (Arrays.binarySearch(m.original, i) < 0)
System.out.println(i);
}
}
}
With Java 8+:
import java.util.stream.IntStream;
public class Main {
private int[] original = new int[] {1, 3, 5, 7, 9};
private int[] random = new int[] {1, 2, 3, 4, 5, 6};
public static void main(String[] args) {
Main m = new Main();
for (int i : m.random) {
if (IntStream.of(m.original).noneMatch(value -> value == i))
System.out.println(i);
}
}
}
Without any libraries:
public class Main {
private int[] original = new int[] {1, 3, 5, 7, 9};
private int[] random = new int[] {1, 2, 3, 4, 5, 6};
public static void main(String[] args) {
Main m = new Main();
for (int i : m.random) {
if (!contains(m.original, i))
System.out.println(i);
}
}
public static boolean contains(int[] array, int value) {
for (int i : array)
if (i == value)
return true;
return false;
}
}
Output:
2
4
6
change this code
public boolean Leaves() {
for (int i = 0; i < head.length; i++) id[head[i] -1] = true;
for (int j = 0; j < id.length; j++) {
if (!id[j]) System.out.print((j +1)+ ",");
}
return true;
}
Im trying to change the negative numbers in the wholeNumbers array to their slot/index-number and then print out the array. Also I have to use a while loop. This is what Ive got so far, but now Im stuck. Am I on the right track copying the array? How do I proceed, is it correct that "change[counter]" be equal to "counter"? Or am my thinking wrong? When i run i get error
public class NegativeNumber {
public static void main(String[] args) {
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int negativeCounter = 0;
int sum = 0;
while(counter < wholeNumbers.length) {
if(wholeNumbers[counter] < 0)
{
sum += wholeNumbers[counter];
negativeCounter++;
}
counter++;
}
System.out.println("Negative numbers: "+negativeCounter);
int[] change = Arrays.copyOf(wholeNumbers, wholeNumbers.length);
while(counter < change.length) { //get error
if(change[counter] < 0){
change[counter]=counter;
System.out.println(change[counter]);
}
}
}
}
}
public static void main(String[] args) {
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int negativeCount;
for(int i = 0; i < wholeNumbers.length; i++) {
if(wholeNumbers[i] < 0) {
negativeCount++;
wholeNumbers[i] = i;
}
}
}
With a while
public static void main(String[] args) {
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int negativeCount;
int idx = 0;
while(idx < wholeNumbers.length) {
if(wholeNumbers[idx] < 0) {
negativeCount++;
wholeNumbers[idx] = idx;
}
idx++;
}
}
here is it:
import java.util.*;
public class NegativeNumber {
public static void main(String[] args)
{
int[] wholeNumbers = {1, 4, 5, -2, -4, 6, 10, 3, -2};
int counter = 0;
int negativeCounter = 0;
int sum = 0;
while(counter < wholeNumbers.length)
{
if(wholeNumbers[counter] < 0)
{
sum += wholeNumbers[counter];
negativeCounter++;
}
counter++;
}
System.out.println("Negative numbers: "+negativeCounter);
int[] change = Arrays.copyOf(wholeNumbers, wholeNumbers.length);
counter = 0; // You forgot to reset this
while(counter < change.length)
{
if(change[counter] < 0)
{
change[counter]=counter;
System.out.println(change[counter]);
}
counter++; // You forgot to increment this
}// while
}// main
}
There were two errors, the counter variable needed to be set back to zero, and into the second while you needed to increment it again (see the comments inside the code).
The output of your program now is:
Negative numbers: 3
3
4
8
Array with duplicates [4,4,1]. Find pairs with sum 5 in O(n).
Expected output (4,1) and (4,1) and count is 2.
Approach#1:
Using HashSet:
public static int twoSum(int[] numbers, int target) {
HashSet<Integer> set = new HashSet<Integer>();
int c = 0;
for(int i:numbers){
if(set.contains(target-i)){
System.out.println(i+"-"+(target-i));
c++;
}
set.add(i);
}
return c;
}
Output is 1.
Approach #2 as stated in this link:
private static final int MAX = 100000;
static int printpairs(int arr[],int sum)
{
int count = 0;
boolean[] binmap = new boolean[MAX];
for (int i=0; i<arr.length; ++i)
{
int temp = sum-arr[i];
if (temp>=0 && binmap[temp])
{
count ++;
}
binmap[arr[i]] = true;
}
return count;
}
Output 1.
However the O(nlog n) solution is using sorting the array:
public static int findPairs(int [] a, int sum){
Arrays.sort(a);
int l = 0;
int r = a.length -1;
int count = 0;
while(l<r){
if((a[l] + a[r]) == sum){
count ++;
System.out.println(a[l] + " "+ a[r]);
r--;
}
else if((a[l] + a[r])>sum ){
r--;
}else{
l++;
}
}
return count;
}
Can we get the solution in O(n)?
You can use your second approach - just change boolean to int:
public static void main(String[] args) {
System.out.println(printPairs(new int[]{3, 3, 3, 3}, 6)); // 6
System.out.println(printPairs(new int[]{4, 4, 1}, 5)); // 2
System.out.println(printPairs(new int[]{1, 2, 3, 4, 5, 6}, 7)); // 3
System.out.println(printPairs(new int[]{3, 3, 3, 3, 1, 1, 5, 5}, 6)); // 10
}
public static int printPairs(int arr[], int sum) {
int count = 0;
int[] quantity = new int[sum];
for (int i = 0; i < arr.length; ++i) {
int supplement = sum - arr[i];
if (supplement >= 0) {
count += quantity[supplement];
}
quantity[arr[i]]++; // You may need to check that arr[i] is in bounds
}
return count;
}
you can try this also
Map<Integer, List> map = new HashMap<>();
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(k - arr[i])) {
count += map.get(k - arr[i]).size();
}
List<Integer> test = map.getOrDefault(arr[i], new ArrayList<>());
test.add(i);
map.put(arr[i], test);
}
return count;
Here is an O(N) Time & Space approach using HashMap.
class Solution
{
static int getPairsCount(int[] arr, int n, int target)
{
HashMap<Integer,Integer> map = new HashMap<>();
int pairs=0;
for (int i=0; i<n; i++)
{
if (map.containsKey(target - arr[i]))
{
pairs += map.get(target - arr[i]);
for (int j=1; j<=map.get(target - arr[i]); j++)
System.out.print("(" +(target-arr[i])+ "," +arr[i]+ ") ");
}
map.put(arr[i] , map.getOrDefault(arr[i],0)+1);
}
return pairs;
}
public static void main (String [] args)
{
int target = 5;
int [] input = {4, 4, 1};
System.out.println(getPairsCount(input , input.length , target));
target = 10;
input = new int [] {1, 6, 3, 2, 5, 5, 7, 8, 4, 8, 2, 5, 9, 9, 1};
System.out.println(getPairsCount(input , input.length , target));
}
}
Output:
2 (Pairs)
(4,1) (4,1)
13 (Pairs)
(5,5) (3,7) (2,8) (6,4) (2,8) (8,2) (8,2) (5,5) (5,5) (1,9) (1,9) (9,1) (9,1)
Basically i have to return an array of n numbers repeated in an array into another array of length m.
my code so far:
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
int count = 0;
for(int j = 0; j < a.length; j++)
for(int i = 0; i < m.length; i++)
if( i == a[j]){
m[i] = count++;
}
}
return m;
} public static void main(String[] args) {
int[] a = {7, 4, 9, 1, 10, 11, 11, 1, 5, 8, 4, 2, 9, 4, 3, 9,
2, 10, 11, 7, 7, 1, 11, 3, 8, 8, 10, 4, 10, 5};
int[] b = frequency(a, 12);
for (int i = 0; i < b.length; i++) {
Std.Out.println(i + "->" + b[i]);
} } }
this is the output im supposed to get
0->0
1->3
2->2
3->2
4->4
5->2
6->0
7->3
8->3
9->3
10->4
11->4
but im getting
0->0
1->21
2->16
3->23
4->27
5->29
6->0
7->20
8->25
9->15
10->28
11->22
what am i doing wrong?
I am not going to give you a different solution, but rather to show the mistakes in your code. If we go with the logic in your code, you have few mistakes:
1) count should be reset to 0 after first loop. Otherwise you will sum up the counts from the previous iterations.
2) count++ should be before the assignment, otherwise it will first assign and then increment. Or you could use ++count.
3) The first loop should be over i.
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
int count;
for(int i = 0; i < m.length; i++) {
count =0;
for(int j = 0; j < a.length; j++)
if( i == a[j]){
count++;
m[i] = count;
}
}
return m;
}
Regards.
This should solve it and do the job!
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
for(int j = 0; j < a.length; j++) {
m[a[j]] += 1;
}
return m;
}
public static void main(String[] args) {
int[] a = {7, 4, 9, 1, 10, 11, 11, 1, 5, 8, 4, 2, 9, 4, 3, 9,
2, 10, 11, 7, 7, 1, 11, 3, 8, 8, 10, 4, 10, 5};
int[] b = frequency(a, 12);
for (int i = 0; i < b.length; i++) {
System.out.println(i + "->" + b[i]);
}
}
}
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
for(int i = 0; i < a.length; i++) //loop through a
if( i < M) //number check
m[a[i]]++; //add one to m at index a[i]
return m;
}
}
this is the right code for the method frequency, also checks to see if the number is in range.