I am trying to finding the sum of each in the below code in java.What changes should i have to made in this code.
import java.io.IOException;
class as {
static void printSubsets(int set[]) {
int n = set.length;
for (int i = 0; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) > 0) {
System.out.print(set[j] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
int set[] = { 1, 2, 3 };
printSubsets(set);
}
}
Output of above code is:
1
2
1 2
3
1 3
2 3
1 2 3
I want To Multiply each element of subset by its last number for e.g.
1*1=1
2*2=4
1*2+2*2=6
3*3=9
likewise all elements
and lastly generate sum of all these subset 1+4+6+9+.. and so on.
Above code also print null set and subset are in order.How this program can be edited to make changes such that it does'nt print null set and print random substring.
As far as I understand your question, you want to multiply all the elements with each other and print out each step of iteration with the result. Here you are:
static void printSubsets(int set[]) {
int sum = 0;
for (int i=0; i<set.length; i++) {
for (int j=i; j<set.length; j++) {
int var = set[i] * set[j];
sum += var;
System.out.println("( " + set[i] + " * " + set[j] + " = " + var + " ) -> sum=" + sum);
}
}
System.out.println("final sum=" + sum);
}
In case of input [1,2,3], the sum is supposed to grow according my algorithm by:
1, 3, 6, 10, 16 up to 20
Just a note about << shift operator which shifts a bit pattern to the left. Let's say that number 2 is understood as 10 in binary. Shifting this number by 2 << 4 will result 100000 in binary that is understood as 32 in decimal. I am not sure you really need this pattern.
Related
I'm making a program that counts how many times each digit (0-9) occurs in each number between 1 to 100. At the end it will say something like:
The digit 0 showed up ____ times between 1-100
The digit 1 showed up ____ times between 1-100
and so forth.
This is what I have:
public class CountEachDigit {
public static void main(String[] args) {
int counter =0;
int[] digit = new int[10];
for (int i=1;i<=100;i++) {
for (int j=0;j<=9;j++){
try{
String a = String.valueOf(i);
String b = String.valueOf(j);
if (b.equals(a.charAt(0)))
counter++;
digit[j]=counter;
} catch (Exception e){
continue;
}
try{
String a = String.valueOf(i);
String b = String.valueOf(j);
if (b.equals(a.charAt(1)))
counter++;
digit[j]=counter;
} catch (Exception e){
continue;
}
try{
String a = String.valueOf(i);
String b = String.valueOf(j);
if (b.equals(a.charAt(2)))
counter++;
digit[j]=counter;
} catch (Exception e){
continue;
}
}
}
for (int j =0;j<=9;j++){
System.out.println("The number "+j+" appears "+digit[j]+" times between 1 - 100.");
}
}
}
I tried changing the charAt each digit to a String to count the occurrence using the try and catch. No dice so far.
You do not need a string operations. You have to use x % 10 to get the last digit, and then x \= 10, to remove this last digit.
public class CountEachDigit {
public static void main(String... args) {
final int lo = 1;
final int hi = 100;
int[] digits = countDigits(lo, hi);
for (int i = 0; i < 10; i++)
System.out.format("The number %d appears %d times between %d - %d.\n", i, digits[i], lo, hi);
}
private static int[] countDigits(int lo, int hi) {
int[] digits = new int[10];
for (int i = lo; i <= hi; i++) {
int val = i;
do {
digits[val % 10]++;
} while ((val /= 10) > 0);
}
return digits;
}
}
Demo:
The number 0 appears 11 times between 1 - 100.
The number 1 appears 21 times between 1 - 100.
The number 2 appears 20 times between 1 - 100.
The number 3 appears 20 times between 1 - 100.
The number 4 appears 20 times between 1 - 100.
The number 5 appears 20 times between 1 - 100.
The number 6 appears 20 times between 1 - 100.
The number 7 appears 20 times between 1 - 100.
The number 8 appears 20 times between 1 - 100.
The number 9 appears 20 times between 1 - 100.
Have an array with int[10] to count the occurrences for each digit.
Then have a function that traverses a string and for each digit it finds increases the correct field in the array.
Then have a loop over numbers from 1 to 100 which converts that number to string and feeds it into the function.
Finally print the array values.
In code this may look like
public class Test {
static int[] occurrences = new int[10];
static void checkOccurrences(String s) {
for (char c: s.toCharArray()) {
if (Character.isDigit(c)) {
occurrences[ c - '0' ]++;
}
}
}
public static void main(String[] args) {
for (int i=1; i<=100; i++) {
String s = String.valueOf(i);
System.out.println("checking "+s);
checkOccurrences(s);
}
System.out.println(Arrays.toString(occurrences));
}
}
and it prints
checking 1
checking 2
checking 3
...
checking 99
checking 100
[11, 21, 20, 20, 20, 20, 20, 20, 20, 20]
In case you or future readers want to see a stream approach, which I doubt, here's what I did just for fun: Stream over the range [1 - 100], convert and map to String, split each String at each charachter such that, for example "42" becomes a stream of "4" and "2", collect to map using digit as key and count of occurrence as value and finally print.
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
// ...
public static void main(String[] args) {
IntStream.rangeClosed(1, 100)
.mapToObj(String::valueOf)
.flatMap(s -> Arrays.stream(s.split("")))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.forEach((k,v) -> System.out.printf("The digit %s showed up %d times between 1-100%n", k, v));
}
Instead of converting a number to string and then loop over its digits, you can also take the remainder by 10, i.e., the last digit, and then divide the number by 10 to "shift" it to the right.
For example, 45 % 10 == 5, and 45 / 10 == 4.
After you exit the while loop, your number is a single-digit number, so you have to count again that digit.
public class CountEachDigit {
public static void main(String[] args) {
int[] digits_count = new int[10];
int min = 1;
int max = 100;
for (int i = min; i <= max; ++i) {
int number = i;
while (number > 9) {
int last_digit = number % 10;
digits_count[last_digit] += 1;
number /= 10;
}
digits_count[number] += 1;
}
for (int i = 0; i < 10; i++) {
int count = digits_count[i];
System.out.println("Digit " + i + " appears " + count + " times in range [" + min + ", " + max + "]");
}
}
}
Using strings:
for (int i = 1; i <= 100; i++) {
String num = String.valueOf(i);
for(int j=0;j<num.length();j++){
//substracting 0 to get the integer value
counts[num.charAt(j)-'0']++;
}
}
for (int i = 0; i < 10; i++) {
System.out.println("The digit " + i + " showed up " + counts[i] + " times between 1-100.");
}
You can do it using by streaming and collecting in a map.
allocate a map to hold the counts
stream the values from 1 to 100 inclusive
within mapMulti
get the last digit by using the remainder % operator
accept the digit and place on the stream
expose the next digit by dividing by 10
Now collect the digits in the map, creating a frequency count as they occur. Each digit will the the key and the value will be the count.
Map<Integer, Integer> counts = IntStream.rangeClosed(1, 100)
.mapMulti((val, consumer) -> {
while (val > 0) {
consumer.accept(val % 10);
val /= 10;
}
}).boxed()
.collect(Collectors.toMap(i -> i, i -> 1, Integer::sum));
counts.forEach((digit, count) -> System.out
.println(digit + " occurs " + count + " times."));
prints
0 occurs 11 times.
1 occurs 21 times.
2 occurs 20 times.
3 occurs 20 times.
4 occurs 20 times.
5 occurs 20 times.
6 occurs 20 times.
7 occurs 20 times.
8 occurs 20 times.
9 occurs 20 times.
I'm solving a problem to find all the multiples of 3 and 5 within a number that is inputted from the user.
I want to show all the multiples and their sum to the user.
I can't find a way to add the values to the array containing the multiples.
Here is the code:
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.*;
public class application {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Input the number from user:
System.out.println("Enter a number to calculate the sum of all the multiples of 3 or 5 below it: ");
int number = input.nextInt();
int i = 1;
int[] arr = {};
System.out.println("The multiples of 3 and 5 below the number " + number + " are: ");
while(i < number) {
if (i % 3 == 0 || i % 5 == 0 ) {
System.out.print(i + ",");
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = i;
}
i++;
}
int sum = IntStream.of(arr).sum();
System.out.println("The sum of these multiples is: " + sum);
//Thank you :D
}
}
Try just adding the multiples together as they are found.
You do not need an array to store them since your code is a) printing out the multiple found and then b) printing out the sum of the multiples
instead of array you can direct sum of the multiple 3 and 5
int sum = 0
inside if statement
if (i % 3 == 0 || i % 5 == 0 ) {
System.out.print(i + ",");
sum += i;
//arr = Arrays.copyOf(arr, arr.length + 1);
//arr[arr.length - 1] = i;
}
and print out the sum
I made the arithmetic mean for whole the sorted array, but now i want to make the arithmetic mean for first sorted half and second sorted half of array.
Ex: My array is: 77, 99, 44, 55, 22, 88, 11, 00, 66, 33.
My code make in first place the sort.
The outcome of program is: 00 11 22 33 44 55 66 77 88 99.
Now i want to make the mean for first half:
00 11 22 33 44 and print it.
Then i want to make the mean for the second half:
55 66 77 88 99 and print it.
public class Array {
private double[] a;
private int NrElmts;
public Array(int max)
{ a = new double[max];
NrElmts = 0;
}
public void elements(double value)
{ a[NrElmts] = value;
NrElmts++;
}
public void print()
{ for(int j=0; j<NrElmts; j++)
System.out.print(a[j] + " ");
System.out.println("");
}
public void selectionSort()
{
int out, in, min;
for(out=0; out< NrElmts -1; out++)
{ min = out;
for(in=out+1; in< NrElmts; in++)
if(a[in] < a[min] )
min = in;
invertPositions(out, min); }
}
private void invertPositions(int one, int two)
{ double temp = a[one];
a[one] = a[two];
a[two] = temp;
}
public void mean()
{
int i;
double sum = 0;
for(i = 0; i < NrElmts; i++) {
sum+=a[i];}
double medie = sum/NrElmts;
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
}
Try this
public void firstHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts/2;
for (i = 0; i < NrElmts/2; i++) { // take sum only till half.
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half the elements
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
public void secondHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts % 2 == 0 ? NrElmts/2 : NrElmts/2 + 1; // If odd, this second array will contain one more element.
for (i = NrElmts/2; i < NrElmts; i++) { // take sum for the next half
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half elements (half + 1) in case of odd length.
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
To calculate the mean for 9, 2 and 7 you have to firstly add them all up, which equals 18 and then divide by how many there are - so 18 / 3 which is 6.
Although, you will have to account for the possibility of an odd list - if there's an odd amount of elements, say for example 1, 2, 3 the middle point of 3 - is 1.5 - and if you're iterating through indexes the iterative variable will count the middle point as 1. So it's a bit tricky, not sure what you'd want to do.Consider the following code though - it does exactly what you want, but with odd list sizes, it will just divide by a decimal value
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
int size = numbers.size();
int iterativeHalf = size / 2;
float meanHalf = (float) size / 2;
float lowerMean = 0;
float upperMean = 0;
for (int i = 0; i < size; i++) {
int realRef = i + 1;
Integer value = numbers.get(i);
if (realRef > iterativeHalf) { //Should be calculating upper mean
if (upperMean == 0) { //if lowerMean is just a running total, not divided yet to get the mean
System.out.println("the lower mean for numbers is " + lowerMean + " / " + meanHalf);
lowerMean = (lowerMean) / meanHalf; //add last value + divide to set it to the mean
}
System.out.println("upper mean = " + upperMean + " + " + value + " = " + (upperMean + value));
upperMean = upperMean + value; //keep the upper values up total going
} else {
System.out.println("lower mean = " + lowerMean + " + " + value + " = " + (lowerMean + value));
lowerMean = lowerMean + value; //keep adding the lower halfs values up
}
}
//When it breaks, must divide upperMean by size to get mean
System.out.println("the upper mean for numbers is " + upperMean + " / " + meanHalf);
upperMean = (upperMean) / meanHalf;
System.out.println(" ");
System.out.println("FINAL lower mean = " + lowerMean);
System.out.println("FINAL upper mean = " + upperMean);
Output is:
lower mean = 0.0 + 10 = 10.0
lower mean = 10.0 + 20 = 30.0
the lower mean for numbers is 30.0 / 2.0
upper mean = 0.0 + 30 = 30.0
upper mean = 30.0 + 40 = 70.0
the upper mean for numbers is 70.0 / 2.0
FINAL upper mean = 35.0
FINAL lower mean = 15.0
This, for a [10, 20, 30, 40] will yield the output shown above but essentially (10+20)/2 as the lower mean and (30+40)/2 for the upper mean.
For [10, 20, 30, 40, 50] will yield (10 + 20) / 2.5 the lower mean and (30+40+50)/2.5 for the upper mean
Only take sum of half the array. Give one more element to your second or first half in case if your array size is odd.
public void firstHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts/2;
for (i = 0; i < NrElmts/2; i++) { // take sum only till half.
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half the elements
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
public void secondHalfMean(){
int i;
double sum = 0;
int numberOFElements = NrElmts % 2 == 0 ? NrElmts/2 : NrElmts/2 + 1; // If odd, this second array will contain one more element.
for (i = NrElmts/2; i < NrElmts; i++) { // take sum for the next half
sum += a[i];
}
double mean = sum / numberOFElements; // sum/half elements (half + 1) in case of odd length.
System.out.format("Mean is: %.1f", mean);
System.out.println("");
}
Since you already have way to make mean for entire array, all you need to do is find mid position of array and then run from and to that point.
In your example: NrElmts is 10, so divide your NrElmnts by 2, so you can get mean for 1 to 5, and then 6 to 10 both 5 each.
Think about situation where you have odd number of elements in array, how do u want to do it, whether in first array or second. let me know if this need help as well.
Steps:
1) create a new variable say a1 to NrElmts/2, and go with your mean function from 1 to a1
2) go from a1+1 to NrElmnts
Let me know if you need any help.
here remember array size and values is defined by user by the help of scanner class and i am using java
task is to find sum of first and last element and 2nd and 2nd last and so on
i already try research but failed
thanks in advance
int sum = 0;
int f = 0;
System.out.println("Your Array is even");
System.out.println("Kinldy enter Your Values of Array");
for(int i = 0 ; i<array.length ; i++)
{
array[i] = s.nextInt();
for(int j = 0 ; j< array.length-i-1 ; j++)
{
sum = j + array.length+1 ;
}
}
System.out.println("Your Sum " + sum);
You could just loop over your array and use the index to find the corresponding numbers from both sides.
The first element can be found by simply doing: array[i].
The corresponding element from the other side can be found by: array[array.length - 1 - i].
The complete code could be something like this:
public static void main(String[] args) {
int[] array = {1, 3, 6, 4, 1, 8};
for(int i = 0; i < array.length / 2; i++)
{
int firstNumber = array[i];
int secondNumber = array[array.length - 1 - i];
int sum = firstNumber + secondNumber;
System.out.println(firstNumber + " + " + secondNumber + " = " + sum);
}
}
Output:
1 + 8 = 9
3 + 1 = 4
6 + 4 = 10
I made the assumption that you only want to do this for half of the array. That's why the for loop is only executed as long as i<array.length / 2. This solution assumes that the length of your array is always an even number. If your array has an uneven length, the middle element will not be considered.
In case you do want to do this for the complete array, all you have to do is remove the / 2 from the for loop statement. The output will be:
1 + 8 = 9
3 + 1 = 4
6 + 4 = 10
4 + 6 = 10
1 + 3 = 4
8 + 1 = 9
This is the code for a method which creates a magic square. n is the length of the square. It has to look like:
static int[][] magicSquare(int n) {
int[][] square=new int[n][n];
I don't understand this k=(k+1)%n; especially, why is it %n ?? Doesn´t that put k to 1 every loop again?
for (int i=0; i<n; i++){
in k=i;
for (int j=0; j<n; j++){
square[i][j]=k+1;
k=(k+1)%n;
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
The % in Java is used for modular division. Whenever the operator is applied the right-hand operand will be subtracted as many times as it can from the left-hand operand and what's left will be the output. You can easily check it by dividing the left-hand operand by the right-hand operand and take the leftover as an integer. In the case of a%b it will be like
a - (a/b)*b.
here are some examples:
10 % 4 = 2 // 2*4 = 8 + 2 = 10
10 % 5 = 0 // 2*5 = 10 + 0 = 10
0 % 4 = 0 // result here is 0 thus 0*4 = 0 + 0 = 0
// if you try to extract 4 from 0, you will not succeed and what's left will be returned (which was originally 0 and it's still 0)...
In your case:
k = (k + 1) % n;
is assuring that the value of k will never exceed 4, thus if it is dividable by 4 then it will be divided and the leftover will be written there. In the case when k is exactly 4 you will have the value of 0 written down into k but since you are always adding k + 1 it is writing the value of 1.
For beginners I do recommend to print the values you are interested in and observe how do the data migrate. Here I've added some printlns for you just to get the idea. Run the code and test it yourself. I do believe the things are going to be a bit cleaner.
public static void main(String[] args) {
int n = 4;
int[][] square = new int[n][n];
System.out.println("--------------");
for (int i = 0; i < n; i++) {
int k = i;
System.out.println("Filling magic cube line " + (i + 1) + ". The k variable will start from " + i + "."); // i initial value is 0 so we add 1 to it just to get the proper line number.
for (int j = 0; j < n; j++) {
System.out.println("Filling array index [" + i + "][" + j + "] = " + (k + 1)); // array indexes start from 0 aways and end at array.length - 1, so in case of n = 4, last index in array is 3.
square[i][j] = k + 1; // add 1 to k so the value will be normalized (no 0 entry and last entry should be equal to n).
k = (k + 1) % n; // reset k if it exceeds n value.
}
System.out.println("--------------");
}
Arrays.stream(square).forEach(innerArray -> {
Arrays.stream(innerArray).forEach(System.out::print);
System.out.println();
});
}
You could always play around and refactor the code as follows:
public static void main(String[] args) {
int n = 4;
int[][] square = new int[n][n];
System.out.println("--------------");
for (int i = 1; i <= n; i++) {
int k = i;
System.out.println("Filling magic cube line " + i + ". The k variable will start from " + i + ".");
for (int j = 0; j < n; j++) {
System.out.println("Filling array index [" + (i - 1) + "][" + (j - 1) + "] = " + k); // array indexes start from 0 aways and end at array.length - 1, so in case of n = 4, last index in array is 3. Subtract both i and j with 1 to get the proper array indexes.
square[i - 1][j - 1] = k;
k = (k + 1) % n; // reset k if it exceeds n value.
}
System.out.println("--------------");
}
Arrays.stream(square).forEach(innerArray -> {
Arrays.stream(innerArray).forEach(System.out::print);
System.out.println();
});
}
Remember that the array's indexing starts from 0 and ends at length - 1. In the case of 4, the first index is 0 and the last one is 3. Here is the diff of two implementations, try to see how does the indexes and values depends both on the control variables i and j.
https://www.diffchecker.com/x5lIWi4A
In the first case i and j both start from 0 and are growing till they it's values are both less than n, and in the second example they start from 1 and are growing till they are equal to n. I hope it's getting clearer now. Cheers