Custom number in Java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to create a custom number class in java, which after ranging from 000000 to 099999 would continue with 0A0000. So the last number would be 9Z9999.
I'm a bit lost on how I could implement this in Java. I suppose I would need to create a custom class which extends Number.
My goal would be to create a class on which I could iterate through (from 000000 to 9Z9999) to reserve document ID ranges.
Although I could do achieve this end with several other workarounds, I find this to be the cleanest solution.
Thank you for any help in advance.

This seems to work. Just use an ordinary number and format it:
static String asStrangeNumber ( int i ) {
// Lowest 4 digits are decimal.
int low4 = i%10000;
i /= 10000;
// Next is base 36 - 0-9-A-Z
int c = i % 36;
i /= 36;
// Remaining should be < 10.
return String.format("%1d%c%04d", i%10, c < 10 ? '0' + c: 'A' + c - 10, low4);
}
public void test() {
test (0);
test (1);
test (10);
test (100);
test (1000);
test (10000);
test (100000);
test (1000000);
}
private void test(int i) {
System.out.println(" "+i+" -> "+asStrangeNumber(i));
}
prints
0 -> 000000
1 -> 000001
10 -> 000010
100 -> 000100
1000 -> 001000
10000 -> 010000
100000 -> 0A0000
1000000 -> 2S0000

I don't think it makes sense. Number defines methods like intValue() etc., and how can you convert 0Z0000 to int?
Just create your own CustomId class, but don't extend Number.

The simplest way to do this is to create a single class that gives out IDs (note these are not numbers per se but words). This would contain 6 counters, each of which had a maximum value (9 for 5 of them 36 for the remaining one that has numbers and letters).
When each new ID is requested the bottom counter is increased, when it reaches it's maximum value it resets to zero and increases the next counter by one etc etc. (this counter could be its own class, with fields for currentValue and maximumValue and method increment() that increments the internal value and returns a boolean as to if the higher counter should be incremented)
Then the actual ID is outputted as a String, with each counter having it's current value converted to a single character (0-9 -->'0'-'9' 10-36 --> 'A'-'Z')

Related

Is there a way to automatically store integers in an ArrayList using a for loop? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My main goal is to get an array that consists of the place values of a number.
for example: if the user input is: 35779
I want this array: {3, 5, 7, 7, 9}
(the user input might change and it can range from 10 to the max possible value of an int.
(int counter is an int that represent how many place values does the input number has. example: when input is: 38557: counter = 5)
ArrayList<Integer> obj = new ArrayList<Integer>();
for(int i = counter-1; i >= 0 ; --i){
int ten2pow = (int)Math.pow(10, i);
int x = input/ten2pow;
obj.add(x);
input = input - x*ten2pow;
}
when doing this and trying to print the array, the output is an empty array
Edit: after changing the for loop initialization and termination condition, the loop worked just fine, and I was able to store the Place values in the ArrayList
I'm going to guess the number is given, if it need to be read from console, then I'm leaving that part out.
Suppose our number is: 35779, then a simple way to "divide" it, digit by digit might be:
Get module 10 result of number
Divide number by 10
Example:
Modulus: 9
number: 3577
Repeat:
Modulus: 7
number: 357
So, this can be done this way:
import java.util.ArrayList;
import java.util.List;
public class NumbersToArray {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
int number = 35779;
while (number > 0) {
list.add(0, number % 10);
number /= 10;
}
System.out.println(list);
}
}
Which prints:
[3, 5, 7, 7, 9]
So, there's no need to get the length of the number
As hinted to by Sotirios Delimanolis in the comments on the question, the first issue here is that the for-loop condition is wrong. i <= 1 will never be true if i starts at a number greater than 1. Also, if the statement were ever to be true (i.e., i is 0 or less than 0), then the increment expression (i--) would run until it underflows to Integer.MAX_VALUE.
Alnitak also mentions in the comments that it would be better to start with the least significant digit. This follows the div/mod algorithm for base conversion, which is more conventional.
The div/mod algorithm for base conversion works by recursively taking a modulo b, where, a is the result of the last modulo operation (starting with the source value) and b is the base to convert to. Each iteration provides another digit for the resulting number by its remainder, starting from the right.
Take for example converting 1000 to base 2:
1000 % 2 = 500, R 0 => ?? ???? ???0
500 % 2 = 250, R 0 => ?? ???? ??00
250 % 2 = 125, R 0 => ?? ???? ?000
125 % 2 = 62, R 1 => ?? ???? 1000
62 % 2 = 31, R 0 => ?? ???0 1000
31 % 2 = 15, R 1 => ?? ??10 1000
15 % 2 = 7, R 1 => ?? ?110 1000
7 % 2 = 3, R 1 => ?? 1110 1000
3 % 2 = 1, R 1 => ?1 1110 1000
1 % 2 = 0, R 1 => 11 1110 1000
You can see how the remainders are used to determine the resulting value. The code to use this algorithm here would look something like this:
ArrayList<Integer> numberList = new ArrayList<Integer>();
int iteratedValue = input;
do {
int currentDigit = iteratedValue % 10;
numberList.add(currentDigit);
iteratedValue /= 10;
} while (iteratedValue > 0);
Collections.reverse(numberList);
A do...while loop is used to ensure that the first digit gets added to the list, even if it is 0.
A deque or other collection could be used to add the items in reverse as an alternative to reversing the list at the end.

I tried to write the program, but it is not working the way I want it. Please tell me what am I doing wrong [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This is the question: Modify the above program to sum all the numbers between 1 to 1000 that are divisible by 7.
This is my code:
int x=1;
int y=1000;
int number=x;
int sum=0;
while (number%7==0) {
sum=sum+number;
++number;
}
System.out.printf("The sum of all numbers divisible by 7 from 1 to 100 is %d", sum);
I don't really like the approach of using a while loop when you know the bounds.
First, start by finding the highest possible :
int maximum = 1000 - 1000 % 7;//994
Then loop from first, until last, by step of 7.
for(int x = 7; x <= maximum; x += 7)
sum += x;
No need to check with slow modulo as we have both bounds and increase by step of 7. Also notice the <=. The = is important here if we want to include the highest.
You could still do it with a while if you want, but in your example you are looping until you find a number which is not divisible by 7. You start at 1, so you will never enter. You need to loop between bounds and verify with an if if the current number is divisible by 7, then you sum.
Again since you know the bounds, the for loop shown above looks cleaner.
For completeness sake, using Java 8 you could achieve this with help of IntStream :
IntStream
.rangeClosed(7, maximum)
.filter(i -> i % 7 == 0)
.sum();
But this will be slower as range only allows incremental of 1 so we process each number and perform a modulo on each.
Try this:
int number=x;
int sum=0;
while (number<y) {
if (number%7==0) {
sum+=number;
}
number++;
}
However there is more effective way. There is no need to loop by one, but loop by 7 and sum these numbers:
int d=7;
int number = (x/d)*d;
int sum=0;
while (number < y-d) {
n+=d;
sum+=n;
}
d represents the divisor.

How to write Fibonacci in one line? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I would like to know how can I write a program that give me as output the Fibonacci sequence (until N member) in one line?
The real obligation of my problem is do this program in one line. I know how can I do it with recursion but in only one line, I haven't any idea how can I do that.
Well, this might be considered cheating, but it works :
Fib(n) = (Math.pow(Phi,n) – Math.pow(–phi,n)) / Math.sqrt(5);
Where Phi = (1 + sqrt(5)) / 2
Or in other words :
public static int fib(int n) {
return (int)((Math.pow((1+Math.sqrt (5))/2,n)-Math.pow((1-Math.sqrt (5))/2,n))/Math.sqrt (5));
}
It's quite accurate.
Test :
public static void main(String[] args)
{
for (int i = 0; i<20; i++)
System.out.println (fib(i));
}
Output :
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
Read more about it here.
Well, here is a one-line JavaScript version of the iterative approach.
function fib(n){var f=[1,1],g=1,h=1,i,t;for(i=2;i<n;i++){t=g+h;g=h;h=t;f.push(t);}return f;}
I expect you are looking for the ternary operator, which lets you compress conditional statements down into a single expression like so:
// returns the nth number in the fibonacci sequence
public static int fib(int n) {
return (n < 2) ? n : fib(n-1) + fib(n-2);
}
P.S.
This should work for both standard seed conditions of
F1 = 1
F2 = 1
or
F0 = 0
F1 = 1
See the Wikipedia article for a complete discussion of the math.

Boolean expression (x / 2) * 2 == x to test [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This is actually one of my lab questions.
You can test to see if an integer, x, is even or odd using the Boolean expression (x / 2) * 2 == x. Integers that are even make this expression true, and odd integers make the expression false. Use a for loop to iterate five times. With each iteration, request an integer from the user. Print each integer the user types, and whether it is even or odd. Keep up with the number of even
and odd integers the user types, and print “Done” when finished, so the user won’t try to type another integer. Finally, print out the number of even and odd integers that were entered.
I basically know what this question requires me to do. However, I don’t quite understand why boolean expression, (x/2)*2 == x, can test whether the integer is an ever number or an odd number. Lets say my number is 59, which is an odd integer obviously. 59 divided by 2 is 29.5. 29.5 times 2, which equals 59. No matter what x is, (x/2)*2 always equals x. So how to make this expression false when the integer is an odd. Then I can determine what I should print.
Because you're dealing with integers, there's always a rounding down to the nearest round number.
59/2 = 29 when all elements are integers.
Multiplying the result by 2 gives 58, so since the 2 numbers aren't the same, we deduce that the number, 59, is odd.
This should be your code written in a beginners way, if u still don't understand something just ask. The formula x==(x/2)*2 is used because when you are dividing two integer variables the result is always a round number, which later if it's odd, won't give u the same initial number. (59/2=29 => 29*2=58 => false)...
import java.util.*;
public class EvenOrOdd{
public static void main( String [] args){
Scanner scan=new Scanner(System.in);
boolean result=true;
List<Integer> EvenNums = new ArrayList<Integer>();
List<Integer> OddNums = new ArrayList<Integer>();
for(int i=0; i<5; i++){
System.out.println("Enter a number: ");
int x=scan.nextInt();
if(x==(x/2)*2){
result=true;
System.out.println(result);
EvenNums.add(x);
continue;
}else if(x!=(x/2)*2){
result=false;
System.out.println(result);
OddNums.add(x);
continue;
}
}
System.out.println("Done");
System.out.println("Even numbers are: " + EvenNums);
System.out.println("Odd numbers are: " + OddNums);
}
}

Detecting Common Elements in an Unsorted Array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I found a code which will detect common elements in an unsorted array. The program runs in linear time! But i did not understand the logic of the program. It would be very helpful if some one could explain the logic of the program.
Here is the code:
public class DeleteUnsortedDataFromArray {
public static List<Integer> findDuplicatesArray(int[] sequence){
int bitarray = 0;
for(int i=0; i< sequence.length; i++){
int x = 1;
x = x << sequence[i];
if((bitarray & x) != 0){
System.out.println("Duplicate found in given array: " + sequence[i]);
} else {
bitarray = bitarray | x;
}
}
return null;
}
public static void main(String[] args) {
int[] input = {1,1,2,3};
findDuplicatesArray(input);
}
}
What it does is to represent each found value as an 1 in a position of the bits composing an integer (bitarray).
The lines:
x = 1;
x = x << sequence[i];
Will put a 1 at the position given by the sequence value+1 (<< is a shift operator).
For example, if sequence[i] value is four, x will have the binary value: ...010000
The line:
(bitarray & x) != 0
Uses bit operation AND to check if a position has been already occupied and hence the valued found.
The problem is that this algorithm only works if your values at sequence are constrained to be low: Between 0 and 30 as there are 32 bits in an Java integer and the value 0 is represented as a 1 at the position 0 of bitarray.
You should consider too what happens when the sequence values are negative.
It works only as long as all values in the array belong to [0, number-of-bits-in-int). If of course you can say 'works' about a function that is supposed to return list of duplicates but always returns null.
You can understand the algorithm as using an array of booleans to test whether a value has occured previously in the array or not. Now instead of using an array of booleans, what you are doing is using the bits in an int to represent whether a value has occured previously or not. The code calls this "bitarray".
To set the Ith bit in an int, you use
x = (x | (1<< i));
Here '|' is the bitwise or operator.
And to test whether the Ith bit has been set you check the condition
if((x & (1<< i)) != 0){
}
here '&' is the bitwise and operator.
Moreover, the algorithm used above will only work if the range of values in the array is between 0 and 31 inclusive. That's because java ints are represented using 32 bits. However it consumes lesser space than other alternatives like using a HashSet or an explicit array of booleans.
However, if space is at a premium, and you know that the range of data in the array is small, you can consider using Bitset class (link).

Categories

Resources