I'm trying to take an array of any length of ints, and concatenate it into a single number without adding it up. For instance, if I have an array that goes as follows
[ 1, 7, 12, 16, 3, 8]
I want to have a variable that will equal 17121638, not equal 47.
I'm supposed to take a input of string and change it into an int without using Interger.parseInt() on the whole input itself.
This is my current attempt:
public static String toNum(String input) {
String [] charArray = new String [input.length()];
int [] parsedInput = new int [input.length()];
for(int i; i < input.length(); i++){
charArray[i] = input.substring(i);
}
for(int c; c < charArray.length; c++){
parsedInput[c] = Integer.parseInt(charArray[c]);
}
Try this:
int[] nums = { 1, 7, 12, 16, 3, 8 };
StringBuilder strBigNum = new StringBuilder();
for (int n : nums)
strBigNum.append(n);
long bigNum = 0;
long factor = 1;
for (int i = strBigNum.length()-1; i >= 0; i--) {
bigNum += Character.digit(strBigNum.charAt(i), 10) * factor;
factor *= 10;
}
Now the bigNum variable contains the value 17121638; in this case it was easier to work with strings. Be careful, if the input array is too big (or the numbers are too big) the resulting value won't fit in a long.
Try to think about how the index of the left most number relates to it's power of 10 in the final number that you're trying to achieve. For example: having an array of [1, 2, 3, 4] should produce the integer 1234. How does the base 10 power of 1000 relate to the length of the array and the index of 1?
I phrase this as a question because I get the sense that this is a homework problem for school .
Variant of Óscar López's solution that doesn't use any parsing (as the question requested):
public class BigNum {
public static void main(String[] args) {
int[] nums = {1, 7, 12, 16, 3, 8};
System.out.println(concatNums(nums));
}
public static long concatNums(int[] nums) {
long result = 0;
long multiplier = 1;
for (int i = nums.length; i > 0; --i) {
int num = nums[i - 1];
while (num != 0) {
result += multiplier * (num % 10);
num /= 10;
multiplier *= 10;
}
}
return result;
}
}
This won't work correctly if the array contains a 0. If that's important, let me know and I'll tweak the algorithm to accommodate it.
Add the numbers together by the join method - that will give you a string and then convert it into a number by the Number function.
you can simply run:
var arr = [ 1, 7, 12, 16, 3, 8];
var num = arr.join('');
Number(num);
First, you want to return an int -- not a String!
Second -- technically -- you could use Integer.valueOf(s); which returns an Integer object with the exact value that .parseInt() would've returned... though I suspect that this would be considered "cheating."
Thirdly, I think this will help you along your way: http://nadeausoftware.com/node/97
Particularly the section titled:
Parsing an integer from a string with custom code
You can use StringBuilder to append each int num from numbers (int[]).
StringBuilder sb = new StringBuilder();
for (int num : numbers) {
sb.append(num);
}
return sb.toString();
one line solution
String str = Arrays.toString(a).replaceAll("\\D", "");
Alright, here's another approach. Although this is similar to another answer, this one can handle some zeros. Just math, no use of Integer.parseInt:
public static int intsToInt(int[] input) {
int total = 0;
int multiplier = 1;
for (int i=input.length-1; i > -1; i--) {
if (input[i] == 0) {
multiplier *= Math.pow(10, String.valueOf(input[i]).length());
}
else {
total += input[i]*multiplier;
multiplier *= Math.pow(10, String.valueOf(input[i]).length());
}
}
return total;
}
public static void main(String[] args) {
int[] ints = {1, 7, 12, 0, 16, 3, 8};
out.println(digitsToInt(ints));
out.println(intsToInt(ints));
}
Here is a simple implementation. Correct if it's wrong please (I'm a beginner).
int concatArray(int[] array){
int sum = 0;
int len = array.length-1;
for(int i=0; i<array.length;i++){
sum += (Math.pow(10, len) * array[i]);
len--;
}
return sum;
}
Related
I want to remove the duplicates by putting them in a new array but somehow I only get a first instance and a bunch of zeros.
Here is my code:
public class JavaApplication7 {
public static void main(String[] args) {
int[] arr = new int[] {1,1,2,2,2,2,3,4,5,6,7,8};
int[] res = removeD(arr);
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + " ");
}
}
public static int[] removeD(int[] ar) {
int[] tempa = new int[ar.length];
for (int i = 0; i < ar.length; i++) {
if (ar[i] == ar[i+1]) {
tempa[i] = ar[i];
return tempa;
}
}
return null;
}
}
expected: 1,2
result: 1,0,0,0,0,0,0....
why dont you make use of HashSet?
final int[] arr = new int[] { 1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8 };
final Set<Integer> set = new HashSet<>();
for (final int i : arr) {
// makes use of Integer's hashCode() and equals()
set.add(Integer.valueOf(i));
}
// primitive int array without zeros
final int[] newIntArray = new int[set.size()];
int counter = 0;
final Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
newIntArray[counter] = iterator.next().intValue();
counter++;
}
for (final int i : newIntArray) {
System.out.println(i);
}
Edit
if you want your array to be ordered
final int[] arr = new int[] { 9, 9, 8, 8, 1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8 };
Set<Integer> set = new HashSet<>();
for (final int i : arr) {
// makes use of Integer's hashCode() and equals()
set.add(Integer.valueOf(i));
}
// priomitive int array without zeros
final int[] newIntArray = new int[set.size()];
int counter = 0;
// SetUtils.orderedSet(set) requires apache commons collections
set = SetUtils.orderedSet(set);
final Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
newIntArray[counter] = iterator.next().intValue();
counter++;
}
for (final int i : newIntArray) {
System.out.println(i);
}
A couple of points to help you:
1) With this: for(int i =0; i<ar.length; i++){ - you will get an IndexOutOfBoundsException because you are checking [i+1]. Hint: it is only the last element that will cause this...
2) Because you're initialising the second array with the length of the original array, every non-duplicate will be a 0 in it, as each element is initialised with a 0 by default. So perhaps you need to find how many duplicates there are first, before setting the size.
3) As mentioned in the comments, you are returning the array once the first duplicate is found, so remove that and just return the array at the end of the method.
4) You will also get multiple 2s because when you check i with i+1, it will find 3 2s and update tempa with each of them, so you'll need to consider how to not to include duplicates you've already found - based on your expected result.
These points should help you get the result you desire - if I (or someone else) just handed you the answer, you wouldn't learn as much as if you researched it yourself.
Here:
int[] tempa = new int[ar.length];
That creates a new array with the same size as the incoming one. All slots in that array are initialized with 0s!
When you then put some non-0 values into the first slots, sure, those stick, but so do the 0s in all the later slots that you don't "touch".
Thus: you either have to use a data structure where you can dynamically add new elements (like List/ArrayList), or you have to first iterate the input array to determine the exact count of objects you need, to then create an appropriately sized array, to then fill that array.
Return statement
As both commenters said, you return from the method as soon as you find your first duplicate. To resolve that issue, move the return to the end of the method.
Index problems
You will then run into another issue, an ArrayIndexOutOfBoundsException because when you are checking your last item (i = ar.length - 1) which in your example would be 11 you are then comparing if ar[11] == ar[12] but ar has size 12 so index 12 is out of the bounds of the array. You could solve that by changing your exit condition of the for loop to i < ar.length - 1.
Zeros
The zeros in your current output come from the initialization. You initialize your tempa with int[ar.length] this means in the memory it will reserve space for 12 ints which are initialized with zero. You will have the same problem after resolving both issues above. Your output would look like this: 1 0 2 2 2 0 0 0 0 0 0 0. This is because you use the same index for tempa and ar. You could solve that problem in different ways. Using a List, Filtering the array afterwards, etc. It depends what you want to do exactly.
The code below has the two first issues solved:
public class JavaApplication7 {
public static void main(String[] args) {
int[] arr = new int[] { 1, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8 };
int[] res = removeD(arr);
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + " ");
}
}
public static int[] removeD(int[] ar) {
int[] tempa = new int[ar.length];
for (int i = 0; i < ar.length - 1; i++) {
if (ar[i] == ar[i + 1]) {
tempa[i] = ar[i];
}
}
return tempa;
}
}
There were a some error mentioned already:
return exits the method.
with arr[i+1] the for condition should bei+1 < arr.length`.
the resulting array may be smaller.
So:
public static int[] removeD(int[] ar) {
// Arrays.sort(ar);
int uniqueCount = 0;
for (int i = 0; i < ar.length; ++i) {
if (i == 0 || ar[i] != ar[i - 1]) {
++uniqueCount;
}
}
int[] uniques = new int[uniqueCount];
int uniqueI = 0;
for (int i = 0; i < ar.length; ++i) {
if (i == 0 || ar[i] != ar[i - 1]) {
uniques[uniqueI] = arr[i];
++uniqueI;
}
}
return uniques;
}
I need to create random numbers that will run through an array without duplicates.
The problem is the duplication and I can't use any of the utils except the Scanner for input (teacher instruction) like java.util.Random or java.util.ArrayList.
I use a function called random that my teacher wrote to us and the function newNum(int num) is where I need what I have asked - random numbers.
package exercise;
import java.util.Scanner;
public class Bingo {
static int size = 10;
static int num;
static int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
private static Scanner sc;
public static void main(String[] args) {
System.out.print("Press Enter to start: ");
sc = new Scanner(System.in);
sc.nextLine();
System.out.println("");
// int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// int[] tempArray = arr;
int num = random();
// int num = sc.nextInt();
// System.out.println(num);
while (size > 0) {
System.out.println(num);
size--;
newArray(num);
num = random();
newNum(num);
// System.out.println(num);
}
}
public static int random() {
int max = 10;
double r = Math.random();
int num = (int) (r * max + 1);
return num;
}
public static int newNum(int num) {
// Here should go the code for the function for getting only new
// random number without duplications
return num;
}
public static int newArray(int num) {
int[] tempArray = arr;
arr = new int[size];
int x = num - 1;
for (int i = 0; i < x; i++) {
if (i < size) {
arr[i] = tempArray[i];
}
}
for (int i = num; i < size; i++) {
if (i < size) {
int y = i - 1;
arr[y] = tempArray[i];
} else {
int a = size - 1;
arr[a] = tempArray[size];
}
}
return num;
}
}
First of all, you write that you can't use shuffle, but that doesn't mean that you are prohibited from implementing it. It's not that hard, actually.
If you want to do that, use the Fisher-Yates shuffle, as found on wikipedia: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
(by the way, since you are going to school, if you find such a wikipedia article - or any other article - to be interesting, you might propose to your teacher to hold an essay on that, easily earned additional good grade)
Of course, this assumes that you have a vector to shuffle, which is inefficient for large vectors ("random numbers within zero to one billion"). In this case you might want to go with:
To find n random numbers within 0..m
1. Initialize an empty list of already used random numbers which is ordered, called "numbers"
2. for i = 0..n-1
2a: r = random(0..m-i) (uniform distribution)
2b: for every entry in numbers
if entry <= r, r++
2c: sort r into numbers (maybe by using a single bubblesort step)
This shifts the complexity from the size of the vector as before to the amount of generated numbers.
Explanation: In every iteration, we want to find an unused number. We find the rth unused number (there is a range of 0..m-i of unused numbers in iteration i). Now we only need to find out which number is the rth unused one. This is done by the inner iteration. We need numbers to be sorted because of this example: current state: numbers = {5, 1}, r = 4. r < 5 -> do nothing. r >= 1 -> r++. End up with r = 5, got a double entry.
If sorting is not wanted for the resulting list, simply go with two lists.
This question already has answers here:
Make individual array values to single number in Python [closed]
(3 answers)
Closed 6 years ago.
Here is my array, it consists of array of integers. Actually, these are the key of my HashMap which consists of some sentences or say "STRING" of a complete paragraph as a key value pair. Now I wanted to join those sentences from taking the key from the integer array one after another in given order.
int[] arr = {3, 2, 0, 5, 3};
HashMap<Integer, String> h = new HashMap<Integer, String>() {{
put(0,"This is my third sentence.");
put(3,"This is my first sentence.");
put(5,"This is my forth sentence.");
put(2,"This is my second sentence.");
}};
The final output should be all the sentences combined as mentioned order and outout should be like a paragraph as :
This is my first sentence.This is my second sentence.This is my third sentence.
This is my forth sentence.This is my first sentence.
Instead of converting the value to a character type you can perform math. For each digit in the array, the corresponding power of 10 is the array length (minus one) minus the index (because Java arrays use 0 based indexing and the last digit corresponds to 100). Something like,
int[] arr = { 3, 2, 0, 5, 3 };
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i] * Math.pow(10, arr.length - i - 1);
}
System.out.println(result);
Output is (as expected)
32053
Optimization
It's possible to optimize the code further by keeping the current power of ten and dividing 10 while iterating each digit. This would also allow the use of a for-each loop like
int[] arr = { 3, 2, 0, 5, 3 };
int result = 0;
int pow = (int) Math.pow(10, arr.length - 1);
for (int digit : arr) {
result += digit * pow;
pow /= 10;
}
System.out.println(result);
Alternatively, iterate the digits from right to left and multiply pow by 10 on each iteration. That might look something like,
int result = 0;
int pow = 1;
for (int i = arr.length - 1; i >= 0; i--) {
result += arr[i] * pow;
pow *= 10;
}
And the above might also be written like
int result = 0;
for (int i = arr.length - 1, pow = 1; i >= 0; i--, pow *= 10) {
result += arr[i] * pow;
}
int number = Integer.parseInt(Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining()));
Yet another way:
int[] arr = {3, 2, 0, 5, 3};
int i = Integer.parseInt(Arrays.toString(arr).replaceAll("[\\[,\\] ]", ""));
System.out.println(i); // prints 32053
Though fairly simple, you should have tried yourself.
Still providing a solution, just debug and understand it.
Working Code
public static void main(String[] args) throws Exception {
int[] arr = {3, 2, 0, 5, 3};
StringBuilder numberStr = new StringBuilder();
for (int item : arr) {
numberStr.append(item);
}
int finalInt = Integer.parseInt(numberStr.toString());
System.out.println(finalInt);
}
Output
32053
First convert the array into string by appending elements one by one and the convert string into integer. Try this code:
public class NewClass63 {
public static void main(String args[]){
int[] arr = {3, 2, 0, 5, 3};
StringBuffer s = new StringBuffer();
for(int i=0;i<arr.length;i++){
s.append(arr[i]);
}
int x = Integer.parseInt(s.toString());
System.out.println(x);
}
}
int[] array = {3,2,0,5,3};
String x = "";
for(int i = 0;i<=array.length-1;i++){
x = x + String.valueOf(array[i]);
}
System.out.println(Integer.parseInt(x));
use a loop:
int[] arr = { 3, 2, 0, 5, 3 };
String itotal = "";
for (int i = 0; i < arr.length; i++)
{
itotal=itotal + String.valueOf(arr[i]);
}
int a = Integer.parseInt(itotal);
There exist various ways.
If I am right, hidden assumption is that the higher element of integer array matches with higher digit of result integer.
int[] arr = {3, 2, 0, 5, 3};
int result = 0;
int power = (int) Math.pow(10, arr.length-1);
for(int element : arr){
result += element * power;
power /= 10;
}
Easiest solution answer is this.
Assume, each alphabet in the example is a single digit.
Empty Array {} : Expected value = 0
{a}: Expected value = a
{a,b}: Expected value = 10*a + b
{a,b,c}: Expected value = 10 * (10*a + b) + c
Code: Test this is online java compiler IDE
public class ConvertDigitArrayToNumber {
public static void main(String[] args) {
int[] arr = {3, 2, 0, 5, 3};
int value = 0;
for (int i = 0; i < arr.length; i++) {
value = (10*value) + arr[i];
}
System.out.println(value);
}
}
This is actually simpler and better solution than the other ones.
Only simple multiplication and addition (No powers).
No String conversions
I am trying to make a code with two arrays. The second array has the same values of the first except for the smallest number. I have already made a code where z is the smallest number. Now I just want to make a new array without z, any feedback would be appreciated.
public static int Second_Tiny() {
int[] ar = {19, 1, 17, 17, -2};
int i;
int z = ar[0];
for (i = 1; i < ar.length; i++) {
if (z >ar[i]) {
z=ar[i];
}
}
}
Java 8 streams have built in functionality that can achieve what you're wanting.
public static void main(String[] args) throws Exception {
int[] ar = {19, 1, 17, 17, -2, -2, -2, -2, 5};
// Find the smallest number
int min = Arrays.stream(ar)
.min()
.getAsInt();
// Make a new array without the smallest number
int[] newAr = Arrays
.stream(ar)
.filter(a -> a > min)
.toArray();
// Display the new array
System.out.println(Arrays.toString(newAr));
}
Results:
[19, 1, 17, 17, 5]
Otherwise, you'd be looking at something like:
public static void main(String[] args) throws Exception {
int[] ar = {19, 1, 17, 17, -2, -2, -2, -2, 5};
// Find the smallest number
// Count how many times the min number appears
int min = ar[0];
int minCount = 0;
for (int a : ar) {
if (minCount == 0 || a < min) {
min = a;
minCount = 1;
} else if (a == min) {
minCount++;
}
}
// Make a new array without the smallest number
int[] newAr = new int[ar.length - minCount];
int newIndex = 0;
for (int a : ar) {
if (a != min) {
newAr[newIndex] = a;
newIndex++;
}
}
// Display the new array
System.out.println(Arrays.toString(newAr));
}
Results:
[19, 1, 17, 17, 5]
I think the OP is on wrong track seeing his this comment:
"I am trying to find out the second smallest integer in array ar[]. I
should get an output of 1 once I am done. The way I want to achieve
that is by making a new array called newar[] and make it include all
the indexes of ar[], except without -2."
This is a very inefficient way to approach this problem. You'll have to do 3 passes, Once to find to smallest indexed element, another pass to remove the element (this is an array so removing an element will require a full pass), and another one to find smallest one again.
You should just do a single pass algorithm and keep track of the smallest two integers,
or even better use a tree for efficiency. Here are the best answers of this problem:
Find the 2nd largest element in an array with minimum number of comparisons
Algorithm: Find index of 2nd smallest element from an unknown array
UPDATE: Here is the algorithm with OP's requirements,
3 passes, and no external libraries:
public static int Second_Tiny() {
int[] ar = {19, 1, 17, 17, -2};
//1st pass - find the smallest item on original array
int i;
int z = ar[0];
for (i = 1; i < ar.length; i++) {
if (z >ar[i]){
z=ar[i];
}
}
//2nd pass copy all items except smallest one to 2nd array
int[] ar2 = new int[ar.length-1];
int curIndex = 0;
for (i=0; i<ar.length; i++) {
if (ar[i]==z)
continue;
ar2[curIndex++] = ar[i];
}
//3rd pass - find the smallest item again
z = ar2[0];
for (i = 1; i < ar2.length; i++) {
if (z >ar2[i]){
z=ar2[i];
}
}
return z;
}
This grabs the index of the element specified in variable z and then sets a second array to the first array minus that one element.
Essentially this gives ar2 = ar1 minus element z
public static int Second_Tiny() {
int[] ar = {19, 1, 17, 17, -2};
int[] ar2;
int i;
int z = ar[0];
int x = 0;
for (i = 1; i < ar.length; i++) {
if (z >ar[i]){
z=ar[i];
x=i;
}
}
ar2 = ArrayUtils.remove(ar, x);
return(z);
}
I need help with creating a VeryLargeInteger class similar to the BigInteger however, as part of my assignment I am not allowed to use BigInteger. I have started off by storing large numbers as strings and then converting them to int[] to perform mathematical functions with them. The problem I am running into is working with two different sized arrays such as:
int[] a = {1, 2, 3, 4, 5} // represents 12,345
int[] b = {1, 2, 4} //represents 124
When I add them I get:
int[] c = {2, 4, 7, 4, 5}
instead of
int[] c = {1, 2, 4, 6, 9}
This is a little messy.
import java.util.Arrays;
public class VeryLargeInteger
{
int[] test, test2;
String temp, temp2;
int size;
VeryLargeInteger(int[] input)
{
int[] test = input;
System.out.println(Arrays.toString(test));
}
VeryLargeInteger(long input1)
{
long input = input1;
temp = Long.toString(input1);
test = convert(temp);
System.out.println(Arrays.toString(test));
}
VeryLargeInteger(String input1)
{
temp = input1;
test = convert(input1);
System.out.println(Arrays.toString(test));
}
public static int[] convert(String input)
{
int [] array = new int[input.length()];
for (int i = 0; i < input.length(); i++)
{
int value = input.charAt(i) - '0';
array[i] = value;
}
return array;
}
VeryLargeInteger add(VeryLargeInteger other)
{
int max = Math.max(this.temp.length(), other.temp.length());
int[] result = new int[max];
int carry = 0;
for (int i = 0; i < max; ++i)
{
int a = i < this.test[i] ? this.test[this.test[i] - i -1] : 0;
int b = i < other.test[i] ? other.test[other.test[i] - i -1] : 0;
int sum = a + b + carry;
carry = sum / 10;
sum -= carry;
result[result.length - i - 1] = sum;
}
VeryLargeInteger added = new VeryLargeInteger(result);
return added;
}
/*
VeryLargeInteger sub(VeryLargeInteger other)
{
}
VeryLargeInteger mul(VeryLargeInteger other)
{
}
VeryLargeInteger div(VeryLargeInteger other)
{
}
VeryLargeInteger mod(VeryLargeInteger other)
{
}
static String toString(VeryLargeInteger other)
{
}*/
public static void main(String[] args)
{
VeryLargeInteger a = new VeryLargeInteger(1050L);
VeryLargeInteger b = new VeryLargeInteger("121123");
VeryLargeInteger c = a.add(b);
}
}
You could pad the second array to get them to add properly:
int[] a = {1, 2, 3, 4, 5};
int[] b = {0, 0, 1, 2, 4};
Then, if your add method compares a[0] to b[0] and so forth, you will get {1, 2, 4, 6, 9}.
An important note I would like to make is this: You are not using the benefit of integers. Integers are 32 bits long, which are 32 digits in base 2. Now, you are using an integers as 1 digit in base 10. By doing this, you are only using 0.0000002% of the memory in a useful way. Use the full range that integers support. The point would be to make an array of integers, but where each integer effectively represents 32 bits of the actual number you want to hold. Adding them together then just goes component-wise, and take care of overflow by using a carry.
To fix the problem as you are facing it now: Align your arrays right. Do not add leading zeroes as Mike Koch suggests, but align them properly, by basically accessing the array elements from back to front, instead of from front to back, as you are doing now. By looking at your code, you have attempted that, but you are having trouble with ArrayIndexOutOfBoundsExceptions I guess. Access both components of the array like this:
int[] number0 = ...;
int[] number1 = ...;
int max = Math.max(number0.length + number1.length) + 1;
int[] result = new int[max];
int carry = 0;
for (int i = 0; i < max; ++i)
{
int c0 = i < number0.length ? number0[number0.length - i - 1] : 0;
int c1 = i < number1.length ? number1[number1.length - i - 1] : 0;
int sum = c0 + c1 + carry;
carry = sum / 10;
sum -= carry;
result[result.length - i - 1] = sum;
}