So my Professor gave us an activity where we input the amount of array and its value. Then Selection sort will be implemented and will display each pass. I manage to do the input part but only managed to display the unsorted and sorted output. I've been wracking my brains on how to show the input of each pass but I always come up short. I saw a code in C/C++ but I don't know how to read the language well enough to understand the code.
This is what the expected output:
Input a number: 5
a[0]: 5
a[1]: 4
a[2]: 2
a[3]: 8
a[4]: 10
UnSorted Array: 5 4 2 8 10
1st Pass: 5 4 2 8 10
2nd Pass: 5 4 2 8 10
3rd Pass: 2 4 5 8 10
Sorted Array Values :2 4 5 8 10
And here's my current output:
Input a number: 5
a[0]: 5
a[1]: 4
a[2]: 2
a[3]: 8
a[4]: 10
UnSorted Array: 5 4 2 8 10
Sorted Array Values: 2 4 5 8 10
This is my code:
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* input number of array
* display array
* 1st pass
* 2nd pass
* 3rd
* 4th
* 5th...
*/
Scanner ss = new Scanner(System.in);
int a, j, temp;
int arr[] = new int[50];
//input number of array
System.out.print("Input a number: ");
int num=ss.nextInt();
System.out.print("");
//display array
for (a = 0; a < num; a++) {
System.out.print("a[" + a + "]: ");
arr[a] = ss.nextInt();
}
//Unsorted Value
System.out.print("UnSorted Array: ");
for (a = 0; a < num; a++) {
System.out.print(arr[a] + " ");
}
System.out.println();
for (a = 0; a < num; a++) {
for(j = a + 1; j < num; j++) {
if(arr[a] > arr[j]) {
temp = arr[a];
arr[a] = arr[j];
arr[j] = temp;
}
}
}
//Passes
//Sorted Value
System.out.print("Sorted Array Values :");
for (a = 0; a < num; a++) {
System.out.print(arr[a] + " ");
}
}
Related
Write a function that receives double-digit numbers, until a number that is not double-digit is received.
• For each number received the program will generate a reverse number and print it. For example : 67 will be printed 76.
• The program will print a count of some of the received numbers thet contains the digit 5 in the digit
Unity (right digit).
I researched the error I got a couple of times but couldn't solve it, if you guys can help much appreciated.
public static void switchInput() {
Scanner star = new Scanner(System.in);
int x=0 , temp=0 , y=1 , i , b=0;
x= star.nextInt();
int[] Switch = new int[x];
//input
for(i=0 ; i<y ; i++){
System.out.println("insert num "+ y + " :");
temp= star.nextInt();
x++;
y++;
Switch[i]=temp;
if(temp<10||temp>99) {
y=i;
}
if(temp%10==5) {
b++;
}
temp=0;
}
star.close();
//Switch
int j , temp2 , temp3=0;
for(j=0 ; j<x ; j++) {
temp3=Switch[j]/10;
temp2=Switch[j]%10;
temp3+=temp2*10;
Switch[j]=0;
Switch[j]=temp3;
}
//print
for(int z = 0;z<x-1;z++) {
System.out.print(" "+Switch[z]+ " ");
}
System.out.println("Number of times 5 was used is : " + b);
}
I got the error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 44 out of bounds for length 44
at hagashaShadi.q1.switchInput(q1.java:37)
at hagashaShadi.q1.main(q1.java:67)
See x= star.nextInt(); here your providing size of array suppose its x=3
which means int[] Switch = new int[3]; but when you are running for loop you are getting like this Switch[4] which is out of bound for the array of size 3. So solution is to use either while loop and insert only when it satisfy the condition and it should break once it cross size of array or if you want to use for loop then break out of loop when i>length-of-array
Have a look at the below code for more understanding
public static void switchInput() {
Scanner star = new Scanner(System.in);
int i=0 , countDigit=0;
List<Integer> numList=new ArrayList<>();
boolean isTwoDigitNumber=true;
//Insert all input number of 2 digit
while(isTwoDigitNumber)
{
System.out.println("insert num "+ (i+1)+ " :");
int temp= star.nextInt();
if(temp%10==5){
countDigit++;
}
if(temp>10&&temp<99) {
numList.add(temp);
i++;
}else {
isTwoDigitNumber=false;
}
}
star.close();
//Switch
//reverse the number and print
for(int j=0 ; j<numList.size() ; j++) {
int num = numList.get(j), reversed = 0;
//System.out.println("Original Number: " + num);
// run loop until num becomes 0
while(num != 0) {
// get last digit from num
int digit = num % 10;
reversed = reversed * 10 + digit;
// remove the last digit from num
num /= 10;
}
System.out.println("reverse Number: " + reversed);
}
//print number of times 5
System.out.println("Number of times 5 was used is : "+countDigit);
}
can anyone help me with this? I am doing this pattern problem in which the user inputs the Starting Number and Number of Lines.
here is my code:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int sn, nl;
try
{
System.out.print("Enter Starting Number: ");
sn = Integer.parseInt(br.readLine());
System.out.print("Enter Number of Lines: ");
nl = Integer.parseInt(br.readLine());
for(int i=nl; i>=sn; i--)
{
for(int j=i; j>=sn; j--)
{
System.out.print(i + " ");
}
System.out.println("");
}
}
catch(Exception e){
}`
the result should be:
Starting number: 5
Number of Lines: 4
8 8 8 8
7 7 7
6 6
5
but im getting no output from my code.
And if i change my Starting number and number of lines to 5 and 6.
i aam getting this result:
6 6
5
The issues comes from the mixing and matching of the nl and sn parameters in your for loops and how the print number is shown.
First specify a separate printNumber that starts from the maximum int printNumber = sn + nl;, then inside the first for loop we can decrease it for every loop printNumber--;
Next the first loop should only focus on the number of lines, for example for(int i=nl; i>0; i--)
The second loop should only focus on the number of items to print in each line, for example for(int j=i; j>0; j--), note how we can use j=i here because the first loop is now working correctly in a descending order.
Then all together it might look something like this:
int printNumber = sn + nl;
for(int i=nl; i>0; i--)
{
printNumber--;
for(int j=i; j>0; j--)
{
System.out.print(printNumber + " ");
}
System.out.println("");
}
Output whet nl = 4 and sn = 5;
8 8 8 8
7 7 7
6 6
5
Steps:
We have to print numbers for sl lines.
We will start the loop with decreasing order of sl (5 --> 4 --> 3 --> 2 --> 1).
Each iteration of sl will have a number that is 1 minus the addition of sn and sl. This is because sn is inclusive.
And in the same iteration, you need to print that calculated number (in point 3) for sl times. For example: if sl is 6 then you have to print the calculated number for 6 times. And in the next decremented iteration which is 5 now, will need to print calculated number for 5 times and so on..
Solution:
private static void solution(int sn, int sl) {
while (sl > 0){
int printNum = (sn + sl) - 1;
for (int j = 1; j <= sl; j++) {
System.out.print(printNum + " ");
}
System.out.print("\n");
sl--;
}
}
Suppose the file sample.txt content is:
1 casual 1 3 5 5
2 casual 5 2 5 3
3 casual 1 5 4 3
4 dress 4 5 4 4
5 athletic 2 4 5 2
Now, what i want is to take the last four numbers and possibly multiply each with four more numbers that will be taken from the user as:
Take the last four digits of the first line i.e. 1 3 5 5
then:
input1x1 + input2x3 + input3x5+ input4x5 = result.
Can anyone help me on how to achieve this, this is the code i have written till now which can read the file and then convert into list. :
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws FileNotFoundException{
FileReader n = new FileReader("sample.txt");
Scanner in = new Scanner(n);
ArrayList<String> lines = new ArrayList<String>();
while (in.hasNext()) {
lines.add(in.nextLine());
}
in.close();
System.out.println(lines.get(1));
// for (int i = 0; i<lines.size()-1; i++) {
// System.out.println(lines.get(i));
// }
}
}
for(int i = 0; i < lines.size() - 1; i++) {
String line = lines.get(i);
String[] parts = line.split(" ");
int result = 0;
result += Integer.parseInt(parts[2]) * 1;
result += Integer.parseInt(parts[3]) * 3;
result += Integer.parseInt(parts[4]) * 5;
result += Integer.parseInt(parts[5]) * 5;
System.out.println(line + " -> " + result);
}
After you run your above code, this gets 4 integers from user and multiplies them with your files numbers
Scanner sc = new Scanner(System.in);
for(int i = 0; i < lines.size(); i++) {
String[] number = lines.get(i).split(" ");
int result = 0;
for (int x=2;x<=5;x++) {
result += Integer.parseInt(number[x]) * sc.nextInt();
}
System.out.println(result);
}
This is a problem in my textbook for my Java class where the user enters 10 integers. The program is supposed to read all integers and only display the unique numbers (not duplicated) as the output. I am having trouble understanding why my output is not picking up the last unique value in the array (5). Can anyone give some insight to this issue? Any help would be appreciated. (Since we are in the early stages of the class and understanding the language, our assignment is to complete this using a nested loop.)
-The output is:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 5
The distinct numbers are: 1 2 3 6 4
-When it should be:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 6
The distinct numbers are: 1 2 3 6 4 5
public class ch7e5{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
int[] numberArray = new int[10];
//create array for all numbers
int[] distinctArray = new int[10];
//create array for distinct numbers
int distinct = 0;
for (int i = 0; i < 10; i++)
numberArray[i] = input.nextInt();
distinctArray[0] = numberArray[0];
//first value will be distinct
for (int i = 1; i < numberArray.length; i++) {
//loop to go through remaining values in numberArray
boolean exists = false;
//create boolean
for (int j = 0; j < numberArray.length; j++) {
//loop to check if value exists already in distinctArray
if (numberArray[i] == distinctArray[j]) {
exists = true;
break;
//break out of inner loop
}
}
if (exists == false) {
//if value is unique then add it to the distinct array
distinct++;
distinctArray[distinct] = distinctArray[i];
}
}
//}
System.out.println("The number of distinct numbers is " + distinct);
System.out.print("The distinct numbers are: ");
for (int k = 0; k < distinct; k++)
System.out.print(distinctArray[k] + " ");
}
}```
There are 3 distinct numbers, 1, 2, and 3 are not any of them as they appear twice. The output should be 6 4 5. I'm not sure how you got 5 distinct numbers here, maybe you inputted them wrong? I would try not using a scanner at first and try putting the numbers in the array manually. Additionally, I would create a boolean array length 10 starting all true to record if numbers are distinct. If a number appears twice, the corresponding boolean in the array will be false. I will update this with code once i have written it.
EDIT: apparently having a duplicate does not delete it from the distinct list. If this is the case, please elaborate on the title.
Here is my code:
public class Main {
public static void main(String[] args) {
int inputs = 3;
int[] numberArray = new int[inputs];
int distinct = 0;
boolean[] mirror = new boolean[inputs];
//just setting up arrays
for(int i = 0; i < numberArray.length; i++) {
//numberArray[i] = i;
mirror[i] = true;
}
numberArray[0] = 1;
//finds out what numbers are not distinct
for (int x = 0; x < numberArray.length; x++) {
for (int y = 0; y < numberArray.length; y++) {
System.out.println("x is " + x);
System.out.println("y is " + y);
if(numberArray[x] == numberArray[y] && x != y) {
System.out.println(numberArray[x] + " is not distinct");
mirror[x] = false;//if current position in array matches any other position, number is not distinct
}
}
}
//calculates how many are distinct
for(int j = 0; j < inputs; j++) {
if(mirror[j]) {distinct++;}
}
//outputs text
System.out.println("The number of distinct numbers is " + distinct);
System.out.print("The distinct numbers are: ");
for(int k = 0; k < inputs; k++){
if(mirror[k]) {System.out.print(numberArray[k] + " ");}
}
}
}
The error was here
distinct++;
distinctArray[distinct] = distinctArray[i];
1, you should increment distinct after adding a number to distinctArray, and 2, you should have done distinctArray[distinct] = numberArray[i]. Right now, you're just putting what is possibly a 0 into distinctArray[distinct].
A shorter way to do it would be this
int[] distinctArray = Arrays.stream(numberArray).distinct().toArray();
System.out.println("The number of distinct numbers is " + distinctArray.length);
System.out.print("The distinct numbers are: ");
for (int d : distinctArray) System.out.print(d + " ");
Output:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 6
The distinct numbers are: 1 2 3 6 4 5
Dear friends I have an assignment and I almost solved it. But I'm having a big problem recently which I couldn't figure a way out for 2 days. If you could help me I would very appreciate it!
So, let's say user entered 5 (N) I immediately create this sequence to get subsets out of it: {1,2,3,4,5}
If N = 4 than the sequence is like: {1, 2, 3, 4} etc.
Than this code below generates all kind of the variations of subsets:
public static int[] genarator(int N)
{
int[] generator = new int[(int) Math.pow(2, N)];
int[] binDigit = new int[(int) Math.pow(2, N)];
for (int i = 0; i < Math.pow(2, N); i++)
generator[i] = (i >> 1) ^ i; // Right Shifting
for (int i = 0; i < Math.pow(2, N); i++)
{
int one = 1;
binDigit[i] = 0;
while (generator[i] > 0)
{
binDigit[i] += (generator[i] % 2) * one;
generator[i] /= 2;
one = one * 10;
}
}
return binDigit;
}
And the way it returns the results like this (In case of: N = 4 {1, 2, 3, 4}) shown here :
1
1 2
2
2 3
1 2 3
1 3
3
3 4
1 3 4
1 2 3 4
2 3 4
2 4
1 2 4
1 4
4
But my lecturer wants from my program to return the result in this order:
1
2
3
4
1 2
1 3
1 4
2 3
2 4
3 4
1 2 3
1 2 4
1 3 4
2 3 4
1 2 3 4
I for now use TreeSet<Long> and parseLong so I can get true results till 1 <= N <= 9. But whenever user enters 10 or higher as N it goes crazy.
To recap, my question is how can I store those numbers which I get from int[] genarator(int N) and display them like my lecturer requires ?
How generator works and how do I get numbers in wrong order? Code is below:
int N = read.nextInt();
int[] sequence = new int[N];
for (int i = 0; i < N; i++)
sequence[i] = i + 1;
int[] tempArray = new int[(int) Math.pow(2, N)];
tempArray = genarator(N);
for (int i = 1; i < Math.pow(2, N); i++)
{
for (int j = 0; j < N; j++)
{
if (tempArray[i] % 10 == 1)
{
System.out.print(sequence[j] + " ");
}
tempArray[i] /= 10;
}
System.out.println();
}
Thank you for checking and I am really sorry for this too long question. But I couldn't make it clear with a short explanation.
What you can do is create a set abstraction that can be compared to other sets. See Java tutorials on Comparators.
//don't call this Set as there is already a Java Set
//interface that youdon't want to confuse yourself with
public class MySet implements Comparable<MySet>{
int[] backingArray;
public MySet(int n) {
//initialize the Set
this.backingArray = generator(n);
}
public static Int[] generator(int n) {
//..whatever you do to generate your results
}
#Override
public int compareTo(MySet otherSet) {
//define how sets are compared (e.g what your professor is asking.
//In your example, if one set is shorter than another,
//it is considered 'smaller')
}
}
Set<MySet> allSets = ....;
and simply invoke Collections.sort(allSets);