My code is here:
import java.util.Arrays;
public class Q1102 {
public static void main(String[] args) {
String temp = "1 3 5 7 6";
int[] array1 = new int[temp.length()];
for (int i = 0; i < temp.length(); i += 2) {
int mounth = Integer.parseInt(String.valueOf(temp.charAt(i)));
array1[i] = mounth;
}
System.out.println(Arrays.toString(array1));
}
}
For some strange reason, the program outputs this:
[1, 0, 3, 0, 5, 0, 7, 0, 6]
Can someone please tell me why this occurs, and how to remove the extra zeros?
I've printed out the values that entered the array as they are entered, and there aren't any extra zeros.
You are using character conversion in a way that only works with single digit numbers, it's fragile in a number of ways. Instead, split the String on whitespace and then parse those tokens. Like,
String temp = "1 3 5 7 6";
String[] tokens = temp.split("\\s+");
int[] array1 = new int[tokens.length];
for (int i = 0; i < tokens.length; i++) {
array1[i] = Integer.parseInt(tokens[i]);
}
System.out.println(Arrays.toString(array1));
Outputs (as I think you expected)
[1, 3, 5, 7, 6]
Here issue in this line temp.length(). It will return 9 as a string length. As you know java takes default value 0. That's why you are getting extra zeros.
import java.util.Arrays;
public class Q1102 {
public static void main(String[] args) {
String temp = "1 3 5 7 6";
int length = (temp.length() + 1)/2;
int[] array1 = new int[length];
for (int i = 0, k = 0; i < temp.length(); i +=2, k++) {
int mounth = Integer.parseInt(String.valueOf(temp.charAt(i)));
array1[k] = mounth;
}
System.out.println(Arrays.toString(array1));
}
Related
I need to write a program, which deletes a number of elements from an int array that are equal to some int value. Eventually I should get an array that isn't bigger than the initial one.
I mustn't use lists or any methods that do the deletion directly.
I tried to do this this way and I can't trace the flaw. I suppose, it should be in the last "for" construction but I'm not sure.
import java.util.Arrays;
import java.util.Scanner;
public class App {
public static void main(String\[\] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Array size: ");
int sizeInput = scan.nextInt();
int[] original = new int[sizeInput];
System.out.print("Array itself: ");
for (int i = 0; i < sizeInput; i++) {
original[i] = scan.nextInt();
}
System.out.println("Number to be deleted: ");
int dNumber = scan.nextInt();
int[] newArr = new int[original.length];
for (int i = 0; i < original.length - 1; i++) {
int sum = 0;
if (original[i] == dNumber) {
newArr[i] = original[i + 1];
sum = sum + 1;
} else if (original[i] != dNumber) {
newArr[i] = original[i + sum];
}
}
System.out.println(Arrays.toString(newArr));
}
}
and here's what I got in my console eventually:
Array size: 5
Array itself: 1 2 3 4 5
Number to be deleted: 2
\[1, 3, 3, 4, 0\]
You see? In the output I get the second "3" for some reason and I also don't get why there's no last element of the initial array.
Please, explain what wrote wrong so that my code doesn't solve the problem. And please explain ho can I solve It. Thanks!
You need a position int for the new array, so you go further only when you set a new value
int[] original = {1, 2, 3, 4, 5};
int dNumber = 2;
int[] newArr = new int[original.length];
int j = 0;
for (int val : original) {
if (val != dNumber) {
newArr[j] = val;
j++;
}
}
newArr = Arrays.copyOf(newArr, j); // truncate
System.out.println(Arrays.toString(newArr));
// [1, 3, 4, 5]
I'm trying to figure out how to take in an integer and rearrange them so that every alternating character is saved (So the [1, 2, 3, 4, 5, 6] would return [1, 4, 2, 5, 3, 6]). I think a queue would be the best to use for this problem so here's what I have so far. It returns [3, 1, 4, 5, 2, 6], but I'm not sure how I can get it to return the alternating form above :
import java.util.*;
public class everyOtherInteger {
public static void main(String[] args) {
Queue <Integer> sort = new LinkedList<Integer>();
String s = "123456";
for (int i = 0; i < s.length(); i++) {
sort.add(Integer.parseInt(s.charAt(i) + ""));
if (i%2 == 0) {
int a = sort.remove();
sort.add(a);
}
else {
}
}
System.out.println(sort);
}
}
Just build the list differently. No queue required.
You can add half the numbers at the start, the add the rest in-between each.
List<Integer> nums = new ArrayList<>();
Scanner sc = new Scanner(System.in);
int limit = sc.nextInt(); // 6
int value = 1;
for (int i = 0; i < limit / 2; i++) {
nums.add(value++);
}
for (int i = 1; i < limit; i+=2) {
nums.add(i, value++);
}
System.out.println(nums); // [1, 4, 2, 5, 3, 6]
I would just add them one after the other in a single loop. The second element is simply the current one plus the offset where the offset is half the array length.
read in the number as a string.
and work with the character array of digits.
Scanner input = new Scanner(System.in);
String val = input.next();
List<Integer> result =new ArrayList<>();
char[] digits = val.toCharArray();
int half = digits.length/2;
for(int i = 0; i < half; i++) {
result.add(digits[i]-'0');
result.add(digits[i+half]-'0');
}
System.out.println(result);
For an input of 123456, prints
[1, 4, 2, 5, 3, 6]
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 am newbie in android developing, i have a simple question.
Imagine I have a long long number, like 166516516516516515.
And i want to have divided output like:
1,6,6,5,1,6,5,1,6,5,1,6,5,1,6,5,...
I mean i want to have every every one in output.
I wrote this algorithm :
int temp = 2536;
ArrayList<Integer> array = new ArrayList<Integer>();
do {
array.add(temp % 10);
temp /= 10;
}
while (temp > 0);
for (int i = 0; i < array.size(); i++) {
Log.i("LOG", "Dynamic Numbers Array Index #" + i + " = " + array.get(i));
}
it works for small numbers (int)
but for long number it doesn't give true work,
How can i solve it to work with big numbers?
thanks.
Just read that stuff into a string and do:
for(char c : str.toCharArray()){}
No need to divide anything and you can have arbitrary length.
If you need ints just convert by doing:
int i = (int)(c - '0');
First of all, you need to watch out if you can "cram" all your number into simple int. Chances are that if it's too long you simply cannot do that at all - as you probably noticed by now.
I took another approach to the solution, but it might not be exactly what you need. Treat the number as a string.
String temp = "166516516516516515";
breakUp(temp);
private static void breakUp(String string){
int length = string.length();
for (int i = 0; i < length; i++) {
String temp = string.substring(i, i+1);
int tempInt = Integer.valueOf(temp);
System.out.print(tempInt + " - "); //or whatever here, you can make function return list instead of void
}
}
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class Callone {
public static void main(String[] args)
{
BigInteger i = new BigInteger("166516516516516515");
List<Integer> list = new ArrayList<Integer>();
BigInteger ten = new BigInteger("10");
while (!i.equals(BigInteger.ZERO))
{
list.add(0, i.mod(ten).intValue());
i = i.divide(ten);
}
System.out.println(list.toString());
}
}
output: [1, 6, 6, 5, 1, 6, 5, 1, 6, 5, 1, 6, 5, 1, 6, 5, 1, 5]
split longString to intArray
Split longString to char array and then use Character.digit to get digit value.
public static int[] splitLong(String longStr) {
int i = 0;
int[] nums = new int[longStr.length()];
for (char l : longStr.toCharArray())
nums[i++] = Character.digit(l, 10);
return nums;
}
Other approach:
public static int[] splitLongNum(String longStr) {
int len = longStr.length();
int[] nums = new int[len];
for (int j = 0; j < len; j++)
nums[j] = Character.digit(longStr.charAt(j), 10);
return nums;
}
I am trying to loop through my array and find all the numbers that are repeating more than once:
E.G: if there is 1 1 2 3 4
It should print saying "1 repeats more than once"
Here is my code and so far what I have tried, however it prints all duplicates and keep going, if there is 4 4 4 4 3 6 5 6 9, it will print all the 4's but i dont want that:
class average {
public static void main(String[] args) throws IOException {
int numOfLines = 0;
int sum = 0, mean = 0, median = 0, lq = 0, uq = 0;
int[] buffer;
File myFile = new File("num.txt");
Scanner Scan = new Scanner(myFile);
while(Scan.hasNextLine()) {
Scan.nextLine();
numOfLines++;
}
Scan.close();
Scan = new Scanner(myFile);
System.out.println("Number Of Lines: " + numOfLines);
buffer = new int[numOfLines];
for(int i=0; i<numOfLines; i++) {
buffer[i] = Scan.nextInt();
}
Scan.close();
Scan = new Scanner(myFile);
for(int i=0; i<buffer.length; i++) {
sum = sum+i;
mean = sum/numOfLines;
}
System.out.println("Sum: " + sum);
System.out.println("Mean: " + mean);
for(int i=0; i<buffer.length; i++) {
for(int k=i+1; k<buffer.length; k++) {
if(buffer[k] == buffer[i]) {
System.out.println(buffer[k]);
}
}
}
Just add the number you will find duplicated to some structure like HashSet or HashMap so you can find it later when you will detect another duplication.
Set<Integer> printed = new HashSet<Integer>();
for(int i=0; i<buffer.length; i++) {
for(int k=i+1; k<buffer.length; k++) {
if(buffer[k] == buffer[i]) {
Integer intObj = new Integer(buffer[k]);
if (!printed.contains(intObj)) {
System.out.println(buffer[k]);
printed.add(intObj);
}
break;
}
}
}
Better O(n) alghorithm:
Set<Integer> printed = new HashSet<Integer>();
for(int i=0; i<buffer.length; i++) {
if (!printed.add(new Integer(buffer[i])) {
System.out.println(buffer[i]);
}
}
You perform the check for every single item of the array, including the first 4, the second 4 and so on. That's why it just doesn't stop and it prints the message multiple times per duplicated element.
You're saying you cannot use a Set and that you don't want to sort your data. My suggestion is that you loop over the array and add each duplicated item to a list. Make sure you check whether the item has already been added. (or use a Set :) )
Then loop over the list and print those items.
I would use a HashMap to store the value I encounter in the array, with the count as a value. So if you encounter a 4, you would look it up in the HashMap, if it doesn't exist, you would add it with a value of 1, otherwise increment the value returned.
You can the loop over the HashMap and get all the values and print the number of duplicates encountered in the array.
Integer[] ints = {1, 1, 2, 3, 4};
System.out.println(new HashSet<Integer>(Arrays.asList(ints)));
Output: [1, 2, 3, 4]
This problem is much simpler and likely faster to solve using a collection. However, as requested here's an answer that uses "just simple array[s]" and no sorting. I've tried not to change your code too much but I refuse to leak resources in the case of an exception.
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
class Average {
public static void main(String[] args) throws IOException {
int numOfLines = 0;
int sum = 0, mean = 0, median = 0, lq = 0, uq = 0;
int[] buffer;
int flag = -1;
File myFile = new File("num.txt");
try (Scanner Scan = new Scanner(myFile)) {
while(Scan.hasNextLine()) {
Scan.nextLine();
numOfLines++;
}
}
try (Scanner Scan = new Scanner(myFile)) {
System.out.println("Number Of Lines: " + numOfLines);
buffer = new int[numOfLines];
for(int i=0; i<numOfLines; i++) {
buffer[i] = Scan.nextInt();
}
}
for(int i=0; i<buffer.length; i++) {
sum = sum+i;
mean = sum/numOfLines;
}
System.out.println("Sum: " + sum);
System.out.println("Mean: " + mean);
//copy every duplicate
int[] dupesOnly = new int[numOfLines];
int dupesOnlyIndex = 0;
for(int i=0; i<buffer.length; i++) {
for(int k=i+1; k<buffer.length; k++) {
if(buffer[k] == buffer[i]) {
dupesOnly[dupesOnlyIndex++] = buffer[i];
//System.out.println(buffer[k]);
}
}
}
//mark all but first occurrence of dupe
boolean[] skip = new boolean[dupesOnlyIndex]; //Inits to false
for (int i = 0; i < dupesOnlyIndex; i++) {
for(int k=i+1; k<buffer.length; k++) {
if(dupesOnly[k] == dupesOnly[i]) {
skip[k] = true;
}
}
}
//skip elements marked as extra dupes
int[] dupesUnique = new int[dupesOnlyIndex];
int dupesUniqueIndex = 0;
for (int i = 0; i < dupesOnlyIndex; i++) {
if (skip[i] == false) {
dupesUnique[dupesUniqueIndex++] = dupesOnly[i];
}
}
//trim to size
int[] dupesReport = new int[dupesUniqueIndex];
for (int i = 0; i < dupesReport.length; i++) {
dupesReport[i] = dupesUnique[i];
}
System.out.println("Dupes: " + Arrays.toString(dupesReport));
}
}
Input file "num.txt" (numbers separated by newlines not commas):
1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3
Output:
Number Of Lines: 14
Sum: 91
Mean: 6
Dupes: [1, 2, 3, 7]
Using the apache commons CollectionUtils.getCardinalityMap(collection):
final Integer[] buffer = {1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3};
final List<Integer> list = Arrays.asList(buffer);
final Map<Integer, Integer> cardinalityMap = CollectionUtils.getCardinalityMap(list);
for (final Map.Entry<Integer, Integer> entry: cardinalityMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey());
}
}
toString() of cardinalityMap looks like this after the init:
{1=4, 2=2, 3=2, 4=1, 5=1, 6=1, 7=2, 9=1}
Using standard java:
final Integer[] buffer = {1, 2, 3, 4, 5, 6, 7, 2, 1, 7, 9, 1, 1, 3};
final List<Integer> list = Arrays.asList(buffer);
final Set<Integer> set = new LinkedHashSet<Integer>(list);
for (final Integer element: set) {
if (Collections.frequency(list, element) > 1) {
System.out.println(element);
}
}