Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am in a intro to Java class. I seem to be having trouble figuring out the algorithm for how i want to go about this.
Currently I need to create and application that generates the number to store in an array element by summing its index and the individual digits of the index. For example, the element with index 17 should be stored as 25... (17+1+7=25) and an element with index 2 would store as 4 (2+0+2=4). I need the program to have 101 elements and then display each value.
I seem to be having trouble figuring out the algorithm for how i want to go about this. Any assistance in the matter would be greatly appreciated.
Thanks in advance. I currently am still researching this matter and am still learning to code so please bear with me.
This is the updated code that I have come up with so far
import java.util.Random;
public class Java_Lab_4 {
public static void main(String[] args) {
int size = 101;
int max = 101;
int[] array = new int[size];
int loop = 0;
Random generator = new Random();
//Write a loop that generates 101 integers
//Store them in the array using generator.nestInt(max);
generator.nextInt(max);
for (int i = 0; i<101; i++)
{
generator.nextInt(max);
}
}
There are surely many ways to achieve this, but the easiest would be repeated division by 10 (another way would be modular arithmetic, taking the index modulo 10).
This means that you would arrive at something like the following algorithm:
int n = i; // i is the index of the current item
while (n > 0) {
int x = n;
if (x > 10) { // we need to deal with the case where i is small
x = n / 10;
}
while (x > 10) { // necessary because we may be dealing with an index > 100
x = x / 10;
} // at this point we have the first digit of the index
a[i] += x; // add this digit to a[i]
n = n / 10; // get rid of the above digit in the calculation. Note that if n < 10, integer division means that n / 10 == 0
} // at the end of this loop, we have added all digits of i to a[i]
a[i] += i; / now we only need to add the index value itself
There are many ways to solve this, and this is a very straightforward and basic approach. I've added ample comments, but please try to work through the code to understand why this works rather than just copying it.
Without posting complete code -- because this is an assignment -- here are some things to consider:
array[a] = a + a;
would give you the solution for indices where a < 10. For two/three digit indices, you need to extract the digits with for example
int nthDigit = Integer.parseInt( // Finally, converts the single-char String to an int
String.valueOf( // converts the char matching the digit to a String
String.valueOf(a).charAt(n))); // converts 'a' first to a String and
// then takes its 'n'th character
where n is 0, 1 or 2. The values of these would then need to be added to the value of the index (a).
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I came across this algorithm on a coding site (There was no author's information) which counts all prime numbers less than a given limit. It looks very similar to SoE algorithm but it is different in the way it counts the primes:
public int countPrimes(int n) {
if (n < 3) return 0;
boolean[] s = new boolean[n];
int c = n / 2;
for (int i = 3; i < Math.sqrt(n); i += 2) {
if (s[i]) continue;
for (int j = i * i; j < n; j += 2 * i) {
if (!s[j]) {
c--;
s[j] = true;
}
}
}
return c;
}
It sets the initial count to half the limit then decrement it, but I can not seem to understand why does this work. Can anyone please explain?
First of all, the boolean array s represents SoE.
The first loop iterates odd numbers from 3 to sqrt(n) (Because all even except 2 is not prime).
At the 6th line, If i is already in the s, continue to next odd number. If not, add all multiple of i that is less or equal to n to s in the second loop.
In addition, the second loop starts from i*i because all multiple of i smaller than i*i are already checked in prior loops.
The count is initialized to n/2 because all even numbers (except 2) are not primes.
And then the loop below can start checking from multiples of 3.
If a new non-prime is found (!s[j]), the count of primes (c) is decreased.
This is a homework problem with a rule that we cant use arrays.
I have to make a program that will generate ten random numbers , append it to a string with a comma after each number.
I then have to give a count of each random number and remove the highest frequency number from the string.
The only issue i cannot solve is how to give a count of each number.
Lets say the string is "1,1,2,4,5,6,6,2,1,1" or "1124566211" with the commas removed.
How can I go about an output something like
1 = 4
2 = 2
4 = 1
5 = 1
6 = 2
Removing all numbers of max frequency
245662
Where the left side is the number and the right is the count.
EDIT: Range is 1 between 10, exclusing 10. It is testing the frequency of each digit i.e. how many times does 1 appear, how many times does 2 appear etc. Also its due tonight and my prof doesnt answer that fast :/
I would use a HashMap. A string representation of the num will be used as the key and you will have an Integer value representing the frequency it occurs.
Loop through the string of nums and put them to the HashMap, if the num already exists in the map, update the value to be the (current value + 1).
Then you can iterate through this map and keep track of the current max, at the end of this process you can find out which nums appear most frequently.
Note: HashMap uses Arrays under the covers, so clarify with your teacher if this is acceptable...
Start with an empty string and append as you go, check frequency with regex. IDK what else to tell you. But yeah, considering that a string is pretty much just an array of characters it's kinda dumb.
You can first say that the most common integer is 0, then compare it with the others one by one, replacing the oldest one with the newest one if it written more times, finally you just rewritte the string without the most written number.
Not the most efficient and clean method, but it works as an example!
String Text = "1124566211"; // Here you define the string to check
int maxNumber = 0;
int maxNumberQuantity = 0; // You define the counters for the digit and the amount of times repeated
//You define the loop and check for every integer from 0 to 9
int textLength = Text.length();
for(int i = 0; i < 10; i ++) {
int localQuantity = 0; //You define the amount of times the current digit is written
for(int ii = 0; ii < textLength; ii ++) {
if(Text.substring(ii, ii+1).equals(String.valueOf(i)))
localQuantity ++;
}
//If it is bigger than the previous one you replace it
//Note that if there are two or more digits with the same amount it will just take the smallest one
if(localQuantity > maxNumberQuantity) {
maxNumber = i;
maxNumberQuantity = localQuantity;
}
}
//Then you create the new text without the most written character
String NewText = "";
for(int i = 0; i < textLength; i ++) {
if(!Text.substring(i,i+1).equals(String.valueOf(maxNumber))) {
NewText += Text.charAt(i);
}
}
//You print it
System.out.println(NewText);
This should help to give you a count for each char. I typed it quickly off the top of my head, but hopefully it at least conveys the concept. Keep in mind that, at this point, it is loosely typed and definately not OO. In fact, it is little more than pseudo. This was done intentionally. As you convert to proper Java, I am hoping that you will be able to get a grasp of what is happening. Otherwise, there is no point in the assignment.
function findFrequencyOfChars(str){
for (i=0; i<str; i++){
// Start by looping through each char. On each pass a different char is
// assigned to lettetA
letterA = str.charAt(i);
freq = -1;
for (j=0; j<str; j++){
// For each iteration of outer loop, this loops through each char,
// assigns it to letterB, and compares it to current value of
// letterA.
letterB = str.charAt(j);
if(letterA === letterB){
freq++
}
}
System.Out.PrintLn("the letter " + letterA + " occurs " + freq +" times in your string.")
}
}
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 have a two dimensional array int arr[][] = new int[47][1]; It holds value from Resultset as arr[i][j] = rs.getInt(2);.Now I want to subtract 10,20,30 consequently till 220 from all rows which I get and then take rows which are near to values 10,20 till 220 .How to subtract these integer values from two dimensional array ??
EDIT 1
I get following sample table through sql query
Through Resultset I'm retrieving beam_current.As you can see from table that there are multiple rowS where value of beam_current is closer to 10,20,30 receptively and this is my exact problem.What I want is a single row corresponding to each beam_current values which are most near to 10, 20 till 220.I don't no how to resolve it through sql query ,therefore I'm doing it through coding.
For one-dimensional array, using the most verbose syntax:
int arr[] = new int[47];
int number = 10;
int i = 0;
while (i < arr.length && number <= 220) {
arr[i] = arr[i] - number;
number = number + 10;
i = i + 1
}
If you had something else in mind, please clarify your requirements.
Here is a working example to solve your problem.
You will first have to read all the values in the database and write them into a float[] (because your values are floats).
Then, call this method with your values.
public static Map<Integer, Float> getClosestValues(float[] databaseValues) {
// We will store the results in this map
Map<Integer, Float> results = new LinkedHashMap<>();
// For each number in 10, 20, 30...210, we are going to look for the closest number
for (int number = 10; number <= 210; number += 10) {
float closest = getClosest(databaseValues, number)
// We have our closest value. Let's store it in the map.
results.put(number, closest);
}
// It's done!
float closestTo10 = results.get(10);
float closestTo20 = results.get(20);
float closestTo30 = results.get(30);
// ...
float closestTo210 = results.get(210);
return results;
}
private static float getClosest(float[] databaseValues, int number) {
float closest = databaseValues[0]; // Init the max with the first value
float closestDistance = Math.abs(number - closest);
for (float currentValue : databaseValues) {
float currentDistance = Math.abs(number - currentValue);
if (closestDistance > currentDistance) {
// We have a shortest distance! Let's update the max
closest = currentValue;
closestDistance = currentDistance;
}
}
return closest;
}
This is absolutely not optimized nor well designed but I detailed each step so that you can understand the process.
You iterate over number which represents you reference numbers.
For each one, you get the closest value from your database values.
To get the closest value for a given number :
Init the closest with the first value
For each new value, if its distance to the number is shortest than the one we had, it is the shortest for now
When you iterated over all your values, your have the closest value!
Is it what you were looking for?
Please check if below code gives you expected output
public static void calculate(){
int arr[] = new int[47];
int number = 10;
int sum =0;
int i=1;
while(number <=220){
sum = sum+number;
number += 10*i;
}
i=-1;
while (++i < arr.length ) {
arr[i] = arr[i] - sum;
}
}
My understanding is you have to substract 10 then 20 then 30 ... till 220 from each row value .
If thats not the requirement then as I have asked in comment please provide sample Data with expected output
Alternate Solution in MYSQL
Alternatively As per my comments and reply from SRV_JAVA . I would propose the solution in MYSQL with the help of of SQL Query
select * from <TableName >where
mod(beam_current,10.0 ) >= 9.97 or mod(beam_current,10.0 )<= 0.03
Hope this will solve the problem
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
Can someone explain to me how to store the previous two fibbonnaci numbers it would help alot in this problem.
public static void main(String[] args) {
int k = 0;
for (int x = 1; x < 13; x++) {
if (k > 2) {
k = (k - 1) + (k - 2);
}
System.out.print(k+" ");
k++;
}
}
when you got number 5 as the printed out put you will set k++ , that will make k=6.
after that k = (k - 1) + (k - 2); output k = (6-1)+(6-2) = 5+4 = 9 , (note : the next should be 8 so your algorithm is wrong)
You have mistaken the Idea of Fibonacci numbers.
the nth Fibonacci number is equal to the sum of previous two Fibonacci numbers. not to the (Fn-1)+(Fn-2)
Edited :
So as you can see if we know the first 2 Fibonacci numbers we can calculate the third by adding those two. and the fourth one will be the summation of second one and third one and it goes ..... to n.
Okay here is a way that you don't need a recursive approach ( you need to store the found Fibonacci numbers in an Array)
okay assume you want to find first n Fibonacci numbers. then create an array of size n and set first and second elements to one (1) since first two Fibonacci numbers are 1 and 1. now loop through the array from 2 to n. at each iteration add the previous two element to the next element.
go through the code. you will find it very easy to do.
public static void fib(int n){
int Fibonacci [] = new int[n];
Fibonacci [0]=1;
Fibonacci [1]=1;
for (int i = 2; i < n; i++) {
Fibonacci [i]=Fibonacci [i-1]+Fibonacci [i-2];
}
System.out.println(Arrays.toString(Fibonacci ));
}
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
So I came across this code on the web and I am trying to wrap my head around how the code is reversing the number order. Can someone help me out? Additionally, is there a way I can change the while loop into a for loop? I don't see an increment so the code is throwing me off just a little.
import java.util.Scanner;
class Challenge{
public static void main(String args[]){
///{write you code here
int n, reverse = 0;
System.out.println("Enter the number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
///}
System.out.println("Reverse is :"+reverse);
}
}
Say your number is 123. The first time through the loop, reverse starts off at 0, so this line, does nothing.
reverse = reverse * 10;
This line, however, takes the last digit of n.
reverse = reverse + n%10;
So now, reverse is 3.
The last line, divides n by 10, discarding any remainder
n = n/10;
So now n is 12.
The second pass through the loop, the following happens:
reverse = reverse * 10;
reverse is now 30.
reverse = reverse + n%10;
reverse is now 32.
n = n/10;
n is now 1.
Last time through the loop:
reverse = reverse * 10;
reverse is now 320.
reverse = reverse + n%10;
reverse is now 321.
n = n/10;
n is now 0.