i am trying to solve some basic java question:
i have an array like int[] x = { 12, 24, 33 };. I need to break it into digits like {1, 2, 2, 4, 3 ,3} and then count the repeating numbers this way: 1:1, 2:2, 3:2, 4:1.
Until now i got this code but i can't save the digits into array.
Can some one help me ?
public class targil_2_3 {
public static void main(String[] args) {
int[] x = { 12, 24, 33 };
int[] ara = new int[x.length * 2];
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < 2; j++) {
ara[j] = x[i] % 10;
x[i] = x[i] / 10;
System.out.println(ara[j]);
}
}
}
}
You dont need to store individual digits, you need to store just count for digits. Lets assume, that you're working with 10 based numbers, then code can looks like
public static void main(String[] args) {
int[] x = { 12, 24, 33, 0, 10, 555 };
int[] count = new int[10];
for (int i = 0; i < x.length; i++) {
int num = x[i];
if (num == 0) {
count[0]++;
continue;
}
while (num > 0) {
count[num % 10]++;
num = num / 10;
}
}
System.out.println(Arrays.toString(count));
}
Output is
[2, 2, 2, 2, 1, 3, 0, 0, 0, 0]
import java.util.Arrays;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class Use {
public static void main(String[] args) {
int[] x = { 12, 24, 33 };
Map<Integer, Long> result = Arrays.stream(x).boxed()
.map(String::valueOf)
.collect(joining())
.chars().boxed()
.collect(groupingBy(Character::getNumericValue, counting()));
System.out.println(result); //prints {1=1, 2=2, 3=2, 4=1}
}
}
Explanation
First line convert an int[] to a Stream<Integer> (for each element)
Convert Stream<Integer> to Stream<String>
Reduce the Stream<String> to String
Create a Stream<Integer> (for each digit)
Count the occurences of each digit in a Map
we have only 10 decimal digits from 0 to 9 , [0..9]
so we make an array with length 10 , like count :
int count[] = new int[10];
for(int i = 0 ; i < x.length ; i++){
if( x[i] == 0 ){
count[0]++;
continue;
}
while(x[i]!=0){
int index = x[i] % 10;
count[index]++;
x[i] /= 10;
}
}
then we will have the number of digits in count array , so we can print it :
for(int i = 0 ; i < 10 ; i++)
System.out.println(i+" : "+count[i]);
if your data is so big it is better to use Map
there are many ways to do this
Digits are 0-9. Build a counter array of size 10, and count each digit extracted in the proper index of the counter array ("counter[digit]++").
Edit: Of- course, in the end you can build the desired result array based on the counter array.
For example: result[0] = "0:" + counter[0];"
Good Luck!
Related
why isn't this code working?
I'm supposed to write a function which removes the odd numbers from an array. here is my code but I don't know where it went wrong. It's giving me an error.
public class Test{
public static int [] removeOdd(int[] input){
int c = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
c++;
}
}
int [] a = new int[c];
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[i] = input[i];
}
}
return a;
}
public static void main(String [] args){
int [] mixedArray = {21, 33, 44, 66, 11, 1, 88, 45, 10, 9};
for (int i = 0; i < mixedArray.length; i++) {
System.out.print(mixedArray[i] + " ");
}
System.out.println();
int [] noOdd = Test.removeOdd(mixedArray);
for (int i = 0; i < noOdd.length; i++) {
System.out.print(noOdd[i] + " ");
}
}
Thanks in advance :)
You need another index variable to access the items of a and not use i:
public static int [] removeOdd(int[] input){
int c = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
c++;
}
}
int [] a = new int[c];
int k = 0;
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[k] = input[i];
k++;
}
}
return a;
}
The index variable i iterates through input and its values do not match and will exceed the permitted values of the indexes of a so I have used k.
The problem is here:
int [] a = new int[c];
for(int i=0; i<input.length; i++){
if(input[i]%2==0){
a[i] = input[i];
}
}
This loop will iterate through the whole input array, and try to insert just the even ones into a, but a is smaller than input, because you allocated space equal to the amount of just the even numbers in input.
In your test case, your a will have size 4, but will try to access the position 6, giving you an out of bound exception.
The problem is that you are trying to insert at a[i] which you could visualise like this:
index: 0 1 2 3 4
input: [1 2 3 4 5]
a: [ 2 4 ]
However, your a array is smaller than your input array, because you have reduced the size to account for the lack of odd numbers. You actually want to do this:
index: 0 1 2 3 4
input [1 2 3 4 5]
a [2 4]
Notice how the index of both even numbers has changed. You were trying to keep it the same.
One way to solve this would be to keep a separate counter variable which tracks where you're up when inserting into a.
int[] a = new int[c];
int sizeOfA = 0;
for (int i = 0; i < input.length; i++)
{
if (input[i] % 2 == 0)
{
a[sizeOfA] = input[i];
sizeOfA++;
}
}
You can simplify the method removeOdd using Streams:
import java.util.Arrays;
public class Test {
public static int[] removeOdd(int[] input) {
return Arrays.stream(input).filter(i -> i % 2 == 0).toArray();
}
public static void main(String[] args) {
int[] mixedArray = { 21, 33, 44, 66, 11, 1, 88, 45, 10, 9 };
for (int i = 0; i < mixedArray.length; i++) {
System.out.print(mixedArray[i] + " ");
}
System.out.println();
int[] noOdd = Test.removeOdd(mixedArray);
for (int i = 0; i < noOdd.length; i++) {
System.out.print(noOdd[i] + " ");
}
}
}
This question already has answers here:
Remove all zeros from array
(11 answers)
Closed 4 years ago.
Can you please advise how can I pass results from an array to another array without some numbers? In this case without zero numbers. Here is my code, I'm stuck.
Result is: [0, 1, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11] - all I want to do, is to create another array and pass there numbers from above without 0's.
Thanks.
public class SieveOfEratosthenes {
public static void main(String[] args) {
int[] myArray = new int[12];
fillArrayWithNumbers(myArray);
System.out.println(Arrays.toString(sieve(myArray)));
}
private static void fillArrayWithNumbers(int[] myArray) {
for (int i = 0; i < myArray.length; i++) {
myArray[i] = i;
}
}
public static int[] sieve(int[] maximumNumber) {
for (int j = 2; j < maximumNumber.length; j++) {
for (int i = j * 2; i < maximumNumber.length; i += j) {
maximumNumber[i] = 0;
}
}
return maximumNumber;
}
}
You can convert your Int[] to a Stream and filter out the zero values.
Code
public static void main(String[] args) {
int[] arr = new int[]{0, 1, 2, 3, 0, 5, 0, 7, 0, 0, 0, 11};
int[] ints = Arrays.stream(arr)
.filter(i -> i != 0)
.toArray();
Arrays.stream(ints).forEach(System.out::println);
}
Output
1
2
3
5
7
11
The solution is above as what infinitezero said to write a for loop that has you array length. Then copy items in the array as length.
for(int i = 0; i < arr.length; i++){
if(arr[i] == 0){
}
else{
arr[i] = arr2[i];
}
I think you can create a new array and fill it with above zero value:
What you want to do it to omit all even numbers (except 2). Then it should be done like this:
public static int[] sieve(int[] maximumNumber) {
int[] result = new int[maximumNumber.length];
int index= 0;
for (int i = 1; i < maximumNumber.length; i++) {
if (i == 2 || i % 2 != 0) { // i is 2 or odd
result[index] = i;
index++; // This will store the real length of the array
}
}
return Arrays.copyOfRange(result, 0, index);
}
I wrote the following code to get all of the numbers from 0 to 1000 that are multiples of three:
public class Hi {
public static void main(String[] args) {
for(int i = 0; i<1000; i++)
if(i % 3 == 0)
System.out.println(i);
}
}
Now I would like to add these numbers together and print the result after the loop.
No need to test for multiplicity of 3 if you iterate by multiples of 3. Finally, to add numbers you should be performing arithmetic. Something like,
long sum = 0;
for (int i = 3; i < 1000; i += 3) {
sum += i;
}
System.out.println(sum);
Or, in Java 8+, using an IntStream (for the same result) like
System.out.println(IntStream.rangeClosed(1, 1000 / 3).map(i -> i * 3).sum());
....And because we all will need java-8 and lambdas oneday...
final List<Integer> myList = new ArrayList<>(Arrays.asList(new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 2, 2 }));
final int sum = myList.stream().filter((i) -> i.intValue() % 3 == 0).mapToInt(Integer::intValue).sum();
System.out.println("Sum of divisible by 3 is " + sum);
As you go through the numbers from 1 to 1000, you can add the multiple of 3 to a list. Then, you could go through that list, and add each number in that list to a sum.
public class Hi {
public static void main(String[] args) {
int[] multiples = new int[1000]; // default initialized with zeroes
mIndex = 0;
for(int i = 0; i<1000; i++) {
if(i % 3 == 0) {
System.out.println(i);
multiples[mIndex] = i;
mIndex++;
}
}
int sum2 = 0;
for(int i2 = 0; i2<mIndex; i2++)
sum2 += multiples[i2];
System.out.println(sum2);
}
}
But that involves going through the numbers twice, and creating another list. It's simpler and more efficient to add the multiple of 3 to a sum as you go from 1 to 1000.
public class Hi {
public static void main(String[] args) {
int sum = 0;
for(int i = 0; i<1000; i++)
if(i % 3 == 0) sum += i;
System.out.println(sum);
}
}
Edit: As the other poster said, there are smarter ways to do this. There are also math formulas for getting this sum in O(1).
Given triangular numbers are as follows:
4
5 3
9 2 21
1 46 12 8
.... upto n rows.
Need to get the highest number from each row and sum it up.
I'm not able to figure out where and how to put all the n rows (like 2D array) and how to select each row from it.
If you can use a List<List<Integer>> instead of array, then your job would be quite easy by using Collections.max method:
// The below syntax is called `double braces initialization`.
List<List<Integer>> triangularNumber = new ArrayList<List<Integer>>() {
{
// Add inner lists to the outer list.
add(Arrays.asList(4));
add(Arrays.asList(5, 3));
add(Arrays.asList(9, 2, 21));
add(Arrays.asList(1, 46, 12, 8));
}
};
int sum = 0;
for (List<Integer> innerList: triangularNumber) {
sum += Collections.max(innerList);
}
System.out.println(sum);
public static void main(String[] args) {
int[][] matrix = { { 4 }, { 5, 3 }, { 9, 2, 21 }, { 1, 46, 12, 8 } };
int sum = 0;
for (int i = 0; i < matrix.length; i++) {
int maxInRow = matrix[i][0];
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
if (maxInRow < matrix[i][j]) {
maxInRow = matrix[i][j];
}
}
sum = sum + maxInRow;
}
System.out.println(sum);
}
Try this:
Why not work with a map? If you need to know each row's index you can do it like this:
Map<Integer, List<Integer>> numbers = new HashMap<Integer, List<Integer>();
as for finding the maximum one can use:
Collections.max(...)
JDK doc
This should do the trick.
What is wrong here? I want delete an item from an array, but it shows me
error ArrayIndexOutBound exception
public class delete {
public static void main(String[]args) {
int i;
//delete item from array
int k[] = new int[]{77,99,44,11,00,55,66,33,10};
//delete 55
int searchkey=55;
int nums=k.length;
for ( i=0;i<nums;i++)
if (k[i]==searchkey)
break;
for (int t=i;t<nums;t++)
k[t]=k[t+1];
nums--;
for (int m=0;m<nums;m++) {
System.out.println(k[m]);
}
}
}
for (int t=i;t<nums-1;t++) //Should be -1 here, as k[t+1] will be out of bounds if t = nums-1
Or another variant to nums-- before you move the numbers
nums--;
for (int t=i;t<nums;t++)
k[t]=k[t+1];
The following rewriting should be instructive:
public class Delete {
static int search(int key, int[] arr) {
for (int i = 0; i < arr.length; i++)
if (arr[i] == key) {
return i;
}
return -1;
}
static void print(int[] arr, final int L) {
for (int i = 0; i < L; i++) {
System.out.println(arr[i]);
// try this also:
// System.out.format("%02d ", arr[i]);
}
}
public static void main(String[] args) {
int nums[] = { 77, 99, 44, 11, 00, 55, 66, 33, 10 };
final int N = nums.length;
int searchKey = 55;
int pos = search(searchKey, nums);
for (int t = pos; t < N-1; t++) {
nums[t] = nums[t + 1];
}
print(nums, N-1);
// prints 77, 99, 44, 11, 0, 66, 33, 10
System.out.println(010 == 8); // prints "true"
System.out.println(00000); // prints "0
}
}
Here are some key observations:
Break apart logic into helper methods. This makes the logical components easier to test and reuse, and the overall logic easier to understand.
It makes the code easier to understand if you use final local variables like N to denote the initial size of int[] nums, and define the rest of the logic in terms of N, N-1, etc.
The more non-final variables there are, the harder it is to understand what's going on as their values changes over time
Follow coding convention. In particular, class names starts with uppercase.
Do be careful with the 00 in the array. The 0 prefix is for octal literals. That is, 010 == 8.
Do note that 00 is printed as simple 0. Numerically, 00 = 000 = 0000 = 0. If you need this to be zero-padded, then that's a formatting issue.
See also
On octal literals
09 is not recognized where as 9 is recognized
Integer with leading zeroes
On zero-padding
Left padding integers with zeros in Java
in the following loop
for (int t=i;t<nums;t++)
k[t]=k[t+1];
when t is pointing to the last element then k[t+1] operation will throw an exception which is what you are getting now.
On k[t]=k[t+1]; you got error es k[t+1] tries to access 10th element with index 9, but your array contains 9 elements. So you got data out of bounds.
It works if you use it as Draco Ater said:
for (int t=i;t<nums-1;t++) {
k[t]=k[t+1];
}
nums--;
Output is then:
77
99
44
11
0
66
33
10
which should be correct. ;-)
for (int t=i;t<nums;t++)
k[t]=k[t+1];
just replace nums with nums-1 because you have already deleted(skipped) one element.
I find it to work best in the following way:
Make sure the iteration does not go beyond the second last element (array.length-1) so it can have an element to compare to:
for(int i=elementPosition-1;i<array.length-1;i++){array[i]=array[i+1];}
import java.util.ArrayList;
import java.util.Arrays;
public class Sort {
public static void main(String a[]) {
int swap;
int length;
int[] unsorted = { 1, 2, 4, 3, 6, 5, 7, 8, 18, 17, 65, 46, 2, 4, 5, 3,
4 };
length = unsorted.length;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (unsorted[i] > unsorted[j]) {
swap = unsorted[i];
unsorted[i] = unsorted[j];
unsorted[j] = swap;
} else if (unsorted[i] == unsorted[j]) {
for (int k = j; k < length - 1; k++) {
unsorted[k] = unsorted[k + 1];
}
length -= 1;
}
}
}
for (int i = 0; i < length; i++) {
System.out.println(" " + i + "th element " + unsorted[i]);
}
}
}