random number different output every time - java

I am coding a secret santa program that prints out the unique secret santa of all participants and does not repeat the output on same input.
My problems are:
The program is generating same output on some reruns...
The program hangs after first run if more than or equal to 3 names present in the list. It prints correct output for only a few entries. For e.g. 3 names it prints secret santas of 2 names and hangs!
The code is as follows.
SecretSanta ss=new SecretSanta();
Scanner scn=new Scanner(System.in);
do
{
System.out.println("Add the participants name:-");
String name=scn.next().trim();
ss.names.add(name);
ss.santa.add(name);
System.out.println("Do u want to add more names?");
System.out.println(" 1-YES 2-NO");
choice=scn.nextInt();
}while(choice==1);
do
{
total_size=ss.santa.size();
System.out.println(total_size);
Collections.shuffle(ss.santa);
System.out.println(ss.names.size());
System.out.println("Below is the list of participants with their secret santas");
Iterator<?> itr=ss.names.iterator();
while(itr.hasNext())
{
String name=(String)itr.next();
String SecretName;
do
{
int rand=r.nextInt(total_size);
SecretName=ss.santa.get(rand);
}while(name.equals(SecretName));
System.out.println(name+" "+SecretName);
ss.santa.remove(SecretName);
total_size=ss.santa.size();
}
ss.santa.addAll(ss.names);
Collections.shuffle(ss.santa);
System.out.println("do you want to rerun??");
System.out.println(" 1-YES 2-NO");
choice=scn.nextInt();
}while(choice==1);

First of all, you can never be sure that a configuration does not repeat. There are just 6 permutations of 3 elements, so each 6th rerun (statistically) the configuration would repeat, assuming that you have 3 items in the list.
Next, about your hangs. You are removing items from the list, and then ask the program to find an element there. Imagine this situation: your names are Fred, Eric, Mike. The choices are
Fred - Eric
Eric - Fred
So you get only Mike in the list and only Mike in the list of santas. See the problem? There is no way to choose a santa. This can be solved in a few ways.
The most simple way is to shuffle names, assume that they are corresponding by indices and check whether anybody is santa for himself. If so, reshuffle. This still has the mentioned problem, but just for the list size one (in which case the problem obviously unsolvable).

The program is generating same output on some reruns because u are using random function and that function can produce repeated numbers (int rand=r.nextInt(total_size);).

Related

What's the best way to split this text file?

basically i have this java assignment in which I need to take the following text file:
https://drive.google.com/file/d/1NqWtApSHovOfSXzVCeU_GPtsCo_m6ZtJ/view?usp=sharing
The legend for the text file is here:
E: did the elector result in promotion (1) or not (0)
T: time election was closed
U: user id (and screen name) of editor that is being considered
for promotion
N: user id (and screen name) of the nominator
V: vote(1:support, 0:neutral, -1:oppose), user id, time, screen_name
And create the following two methods:
Given a user id, output the total number of times the user has voted to support or be neutral or oppose the candidate considered for promotion
for all people the user has voted for collectively in all the elections.
Given a user id considered for promotion, output the user id and
screen name of the nominator. For multiple nominations, you will
output all nominators. If the user is not nominated ever, output
an appropriate message.
I'm really lost on how I should go about splitting the text file into pieces to help me obtain the information needed to create the two methods. Any insight would really be great
Basically you need to create different string reader loops that iterate over the text file line by line. Nobody here will do this for you because it´s to much work, and it´s your work!
Here´s a discussion about iterating-over-the-content-of-a-text
You can use the str.split() method. You write the point in the text at which you would like to split in the brackets.
For example if you have the following;
String str "Hello world";
String [] arrayString = str.split (" ");// splits the string at the space
for( String a:arrayString);
System.out.println(a);
Output:
Hello
World

Check input continuously on one line?

I am trying to make a simple code which continously checks the user input on if the number is positive or negative and that it would all be on 2 lines.
First line being the user input and the second line being the output.
I am a beginner in coding and am not such a professional, but I have right now put the Scanner object in a while loop and it checks if the user input is positive. If it's negative then it would stop the program.
import java.util.Scanner;
public class basic {
public static void main(String[] args){
int numb;
Scanner scanner = new Scanner(System.in);
System.out.println("Fill in a random number which ain't negative!");
while((numb = scanner.nextInt()) > 0) {
System.out.println("Again!");
}
{
System.out.println("This is a negative!");
System.exit(1);
}
}
}
What I want to do is that I get this as an output and only on 2 lines:
1 2 3 4 5
Again!
And if I input a negative number on the line that it changes the 'Again!' to 'This is a negative!'
1 2 3 4 5 6 -8
This is a negative!
But with the code I have now I can only get this as an output and would get much more than just 2 lines:
1
Again!
2
Again!
-3
This is a negative!
This is console output so cannot be overwritten.
But if you are really looking to the getting required o/p printed on the console, you can use list and keep pushing digits to it and print all the items of the list.
You could use \r to rewrite the last line. Consider that:
System.out.println("\r"+yourOutput+" > ")
It replaces the last line in the console with this one, that's how loading bars in linux are done by the way :D. Use this method to display your previous inputs/numbers. User input will be in the second line. When user has pressed enter and your program has gotten the user input as string, process it and do the same thing again, this time with yourOutput updated with new info:
System.out.println("\r"+yourOutput+" > ")
Let me welcome you to your first post on StackOverflow!
It is unusual to have java applications clearing the console output. That being said, it is possible, but not without calling OS commands. As mentioned in comments, this is a little beyond beginner material if you do this.
If you want to try it though, as seen here, you can clear the console by executing a native OS command. If you use the below code (copied from the link with a minor edit)
public static void clrscr(){
//Clears Screen in java
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (Exception e) {}
}
you can call this with clrscr() in your code and you should be able to clear the screen.
Now looking at your code, you won't just be able to slip this in as you will clear the output, thus clearing the past numbers. If you want it the way that you described where you have all the user's output displayed in succession, you'll need to re-print all their entries each time you clear the screen. Thus each time you get a user's input:
You'll want to take that input and add it to a list of numbers
Clear the screen
Output that entire list
Output your evaluation
Let me know if you have questions. :-)

Last iteration of for loop not outputting

Forgive me if this is not formatted properly, this is my first post. I looked to see if this issue has been found before and I cannot find anyone who has had the same problem I am having.
I am trying to learn Java and cannot for the life of me figure out why my for loops are not outputting the last iteration. I am going through codeabbey's exercises and completed the first two relatively easily. However on the third and fourth problems, I cant get my for loop to output during the last iteration.
I began looking on google and thought I would compare my answer to someone else's. I couldn't see why mine wouldn't work when my code was almost identical to the person I found. So I copied their code and to my surprise I had the same problem when this code also would not output on the last iteration.
So, here is the context.
The website gives you a single number first which is the number of sets of the following numbers. For the third problem, you are to add the sets of two, output the sum followed by a space and loop through the entire batch. For the fourth problem, it is similar where the first number is the number of sets in the batch but you are to compare the two numbers and output the lower number. I will copy my code here for the third problem because the code is simpler.
Here is the code:
import java.util.Scanner;
public class Summation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n;i++){
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b + " ");
}
}
}
Here is the input you are to copy and paste:
3
100 8
15 245
1945 54
and this is my output:
108 260
So, as you can see we are missing the last output here. I tried changing the for loop to (i < (n+1) ) which still didn't change anything. Any help would be GREATLY appreciated!
Ok so I tested it, and with your numbers, typing them in one by one it works. Copy pasting them, press enter one more time at the end of the copy. If you don't press enter, the scanner thinks you're still adding to the second number so it won't continue until enter is pressed.
I would try using println() as someone else suggested, or calling flush() at the end of the program to make sure something isn't being held in a buffer and not being written.

I'm having trouble with a codeabbey assignment, just need a push on how to start

I don't want the answer, I just don't understand how to scan the first number to tell the program how many pairs there are. If you could nudge me in the right direction I would greatly appreciate it.
"Most programs should be able to make some choices and decisions. And we are going to practice conditional programming now.
This is usually done by a kind of if ... else statements which may look like:
IF some_condition THEN
do_something
ELSE
do_other_thing
ENDIF
Depending on your programming language syntax could be different and else part is almost always optional. You can read more in wikipedia article on Conditional statements.
Of two numbers, please, select one with minimum value. Here are several pairs of numbers for thorough testing.
Input data will contain number of test-cases in the first line.
Following lines will contain a pair of numbers to compare each.
For Answer please enter the same amount of minimums separated by space, for example:
data:
3
5 3
2 8
100 15
answer:
3 2 15 "
Firstly, you might want to format your example data a bit. I understood it, but mostly only because I've seen that question format before.
Well, to answer your question but not the question's question (heh), note this:
Following lines will contain a pair of numbers to compare each.
Note the "lines" (plural) and the "each." We're going to need a loop.
We also know each line is a test case.
So modify the instructions:
Loop over the following test cases, comparing each pair
But how many times do we loop?
Input data will contain number of test-cases in the first line
That's the first number.
So here's our code skeleton:
//We can use a Scanner for convenience, it has a readInt() method
Scanner input = new Scanner(/*your input*/);
int numCases = input.readInt();
for(int i = 0; i < numCases; i++) {
int first = input.readInt(); //readInt() will also skip newlines, just a tip.
int second = input.readInt();
/* Compare two inputs, do stuff*/
}
For the record, you could also simply ignore the first input and just loop until there is no more input, but that's sloppy.
First you need to create a Scanner. If you're reading from the console, then this will work:
Scanner scan = new Scanner(System.in);
If you need to read from a file, then you can add this line as well.
System.setIn(new FileInputStream("inputFileName"));
For your specific case, you can do something like:
int numPairs = scan.nextInt();
You can find out more about Scanner and its methods from the Oracle documentation here.

Getting each different numbers separately and examining them in java

I am new to java and i want to make a program where i want to get the integers the user has input, and look at what different numbers they are. and move them around as well as add stuff between them.
For example:
Enter number
User input: 123456
after that i want to see what the first number is, which is 1 or what the third number is which is 3. i want to be able to get those different information. and play around with them, for example add the sixth and the first number and print it out for the user.
Which technique in java allows me to do that, what is the name so i could study it more.
if there is a video online teaching that, it would also be great.
Thanks.
ps. i know the basics, i dont need to know how to do the second part playing with the numbers i just dont know how to tell what the first or second number in the lists of number is.
Eg: 123456
Convert the int to string keep the int also
1) String.valueOf(number)
2) Integer.toString(number)
get the length of the string using String.length();
the if you want the 3rd number
Use the int value for the following operation
Eg: 123456 (3rd number 3) Since you have the length of the string you know what will be the divisor
divide using 10 * 10 * 10 this will 123456/1000 = 123
Then % it with 10 always you can put these within a methos to get any position
Try the below code :You are taking an integer input and converting it into a string
public class InputNumberProgram {
public static void main(String[] args) {
Integer i = 5678;
// Convert your input to a string
String s = Integer.toString(i);
System.out.println("Length of input:" + s.length()); System.out.println(Integer.parseInt(s.valueOf(s.charAt(0)))+Integer.parseInt(s.valueOf(s.charAt(1))));
}
}
If you read it as a String and do what you want with String methods
For example you have String number. To get i-th symbol you can use number.charAt(i)

Categories

Resources