There is a voice recorder which stores student voice as per roll number on which it was heard earlier. When the attendance process is complete, it will provide a list which would consist of the number of distinct voices. The teacher presents the list to you and asks for the roll numbers of students who were not present in class.
I'm trying to find out roll number of absent students in increasing order.
I wrote this case but some test cases are failing. I'm not sure what values would be in list which is provided by teacher.
There are only two inputs:
no of student
result from voice recorder
So can anyone tell what is missing here
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
List<Integer> ll = new ArrayList<>();
List<Integer> input = new ArrayList<>();
for (int i = 1; i <= n; i++) {
ll.add(i);
}
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
input.add(Integer.parseInt(strs[i]));
}
for (int i = 0; i < ll.size(); i++) {
if (input.contains(ll.get(i))) {
continue;
}
else {
System.out.print(ll.get(i));
}
if (i != ll.size() - 1) {
System.out.print(" ");
}
}
}
This works fine and every test case passed.
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int stdCount = Integer.parseInt(br.readLine());
String rollNumbers = br.readLine();
TreeSet<Integer> presentStudents = new TreeSet<Integer>();
String[] rollNoArr = rollNumbers.split(" ");
for(String s : rollNoArr) {
presentStudents.add(Integer.valueOf(s.trim()));
}
for(int i = 1; i <= stdCount; i++) {
if(!presentStudents.contains(i)) {
System.out.print(i);
if(i < stdCount) System.out.print(" ");
}
}
}
Assuming that I'm reading the question correctly, you first input the total number of students in the class. Each student has an assigned number, and you next provide a list of numbers (cooresponding to students present in class) seperated by spaces. Your code was missing a few brackets, which messed things up.
In addition, for this specific case, your logic of:
if (true) {
continue;
}
else{
// Do something
}
Can be made a lot simpler by doing:
if(!true){
// Do something
}
Here is the final code that I touched up:
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
List<Integer> ll = new ArrayList<>();
List<Integer> input = new ArrayList<>();
for (int i = 1; i <= n; i++) {
ll.add(i);
}
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
input.add(Integer.parseInt(strs[i]));
}
for (int i = 0; i < ll.size(); i++) {
if (!input.contains(ll.get(i))) {
System.out.print(ll.get(i));
if (i != ll.size() - 1) {
System.out.print(" ");
}
}
}
}
An input of:
6
1 3 4
Results in an output of:
2 5 6
////working code using Java8
{
public static void main(String[] args) throws IOException {
List<Integer> totalRolls;
String[] inputRollsWithProxyStudentsRoll;
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
totalRolls = IntStream
.rangeClosed(1, Integer.parseInt(br.readLine()))
.boxed()
.collect(Collectors.toList());
inputRollsWithProxyStudentsRoll = br.readLine().trim().split("\\s+");
}
List<Integer> rollsWithProxyStudentsRoll = Arrays
.stream(inputRollsWithProxyStudentsRoll).map(Integer::parseInt)
.collect(Collectors.toList());
IntStream
.range(0, totalRolls.size())
.filter(i -> !rollsWithProxyStudentsRoll.contains(totalRolls.get(i)))
.forEach(i -> {
System.out.print(totalRolls.get(i));
if (i != totalRolls.size() - 1) System.out.print(" ");
});
}
}
import java.io.*
import java.util.*;
class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = sc.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n; j++) {
if (i == array[j]) {
break;
}
if (j == n - 1 && i != array[j]) {
System.out.println(i + " ");
}
}
}
}
}
Related
Hello I've been getting this error in Kattis, 'Run time error' while all my test cases are correct in my own machine. Tested everything but as soon as i run this in kattis i get a run time error. Can you guys help me figure this out? Ive been debugging for hours but i am struggling.
https://open.kattis.com/problems/throwns?editsubmit=9372235 :Link of the problem
import java.util.*;
import java.io.*;
public class GOT{
public static void main(String[] args)throws IOException{
BufferedReader bi = new BufferedReader(new I
nputStreamReader(System.in));
int[] parseLine1 = new int[2];
String[] strLine1;
strLine1 = bi.readLine().split(" ");
//Parsing of 1st line of inputs i.e. N and K
for (int i = 0; i < strLine1.length; i++) {
parseLine1[i] = Integer.parseInt(strLine1[i]);
}
//init of Kids array
int[] nKids = new int[parseLine1[0]];
String[] commands = new String[parseLine1[1]];
int i;
for(i = 0; i < nKids.length; i++){
nKids[i] = i;
}
//parsing of 2nd line which are the commands
String strLine2;
String[] nCommands;
Scanner sc = new Scanner(System.in);
strLine2 = sc.nextLine();
nCommands = strLine2.split(" ");
int holder=0;
ArrayList<Integer> tracker = new ArrayList<Integer>();
int exit;
int throwns;
int undoCtr=0;
for(i = 0; i<nCommands.length; i++){
if(nCommands[i].equals("undo")){
nCommands[i] = nCommands[i].replaceAll("undo","101");
}
}
exit = nCommands.length;
i = 0;
while(exit != 0){
//System.out.println(Integer.parseInt(nCommands[i]));
if(Integer.parseInt(nCommands[i]) > 0){
for(int k = 0; k< Integer.parseInt(nCommands[i]); k++){
holder++;
if(holder==nKids.length){
holder = 0;
}
}
}if(Integer.parseInt(nCommands[i]) < 0){
for(int k = Integer.parseInt(nCommands[i]); k<0 ; k++){
holder--;
if(holder==0){
holder = nKids.length;
}
}
}else if(Integer.parseInt(nCommands[i]) == 101){
i++;
undoCtr = Integer.parseInt(nCommands[i]);
while(undoCtr!=0){
tracker.remove(tracker.size()-1);
undoCtr--;
}
exit--;
}
tracker.add(holder);
exit--;
i++;
}
System.out.println(tracker.get(0));
}`
}`
Your approach is too complex for a 2.8 difficulty problem. If you find yourself writing more than 25 lines of code, it's usually time to take a step back and re-think your approach.
Here's the algorithm that worked for me:
Make a list of "final" throw commands, initially empty.
Loop over the input tokens and analyze each command:
If a command is a number, append to the command list.
If a command is an undo n, pop the command list n times.
Now sum the commands in the list and print the mod of this sum, taking care to keep the mod positive.
Here's the spoiler:
public class Throwns {
public static void main(String[] args) {
var sc = new java.util.Scanner(System.in);
int n = Integer.parseInt(sc.nextLine().split(" ")[0]);
var line = sc.nextLine().split(" ");
var commands = new java.util.ArrayList<Integer>();
int sum = 0;
for (int i = 0; i < line.length; i++) {
if (line[i].matches("^-?\\d+$")) {
commands.add(Integer.parseInt(line[i]));
continue;
}
for (int j = Integer.parseInt(line[++i]); j > 0; j--) {
commands.remove(commands.size() - 1);
}
}
for (int c : commands) {
sum += c;
}
System.out.println(Math.floorMod(sum, n));
}
}
This was a question i came across when i was generally practicing some java questions online . I concentrated on finding the most frequent words as i thought that coding the least frequent words would be easy. I finally managed to code the most frequent words part but I'm unable to code the least frequent words part. Expecting a help from you guys
Thanks in advannce
This is the code for the most frequent part
import java.io.*;
public class wordFreq {
private static String[] w = null;
private static int[] r = null;
public static void main(String[] args){
try {
System.out.println("Enter 'n' value :: ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
w = new String[n];
r = new int[n];
FileReader fr = new FileReader("acq.txt");
BufferedReader br = new BufferedReader(fr);
String text = "";
String sz = null;
while((sz=br.readLine())!=null){
text = text.concat(sz);
}
String[] words = text.split(" ");
String[] uniqueLabels;
int count = 0;
uniqueLabels = getUniqLabels(words);
for(int j=0; j<n; j++){
r[j] = 0;
}
for(String l: uniqueLabels)
{
if("".equals(l) || null == l)
{
break;
}
for(String s : words)
{
if(l.equals(s))
{
count++;
}
}
for(int i=0; i<n; i++){
if(count>r[i]){
r[i] = count;
w[i] = l;
break;
}
/* else if(count==1){
System.out.println("least frequent");
System.out.println("("+w[i]+":"+r[i]+"),");
}*/
}
count=0;
}
display(n);
} catch (Exception e) {
System.err.println("ERR "+e.getMessage());
}
}
public static void display(int n){
System.out.println("Most Frequent");
for(int k=0; k<n; k++){
System.out.print("("+w[k]+":"+r[k]+"),");
}
}
private static String[] getUniqLabels(String[] keys)
{
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for(int i=1; i<keys.length ; i++)
{
for(int j=0; j<=uniqueKeyIndex; j++)
{
if(keys[i].equals(uniqueKeys[j]))
{
keyAlreadyExists = true;
}
}
if(!keyAlreadyExists)
{
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
}
Hello I can't make this work, I am given a main word followed by another sub words if the word is contained in the main word the part should be deleted.
//Example
//fmrog (in.nextLine)(main word)
//4 (in.nextInt)(the amount of sub words)
//roc(in.nextLine)(not contained)
//gor(in.nextLine)(not contained)
//rog(in.nextLine)(contained)
//ogr(in.nextLine)(not contained)
//result:fm
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder mainWord = new StringBuilder(in.nextLine);
int n = in.nextInt();
StringBuilder MainWord2 = new StringBuilder(mainWord);
in.nextLine();
for (int i = 0; i < n; i++) {
String subWord = in.nextLine();
int chars = subWord.length();
if (chars> mainWord.length()){
continue;
}
for (int j = 0; j < subWord.length(); j++) {
int r = 0;
for (int k = 0; k < mainWord.length(); k++) {
r++;
if (k > MainWord2.length() - 1) {
break;
}
if (MainWord2.charAt(k) == subWord.charAt(j)) {
break;
}
}
if (r <= MainWord2.length() && MainWord2.charAt(r-1) == subWord.charAt(j)) {
MainWord2.deleteCharAt(r - 1);
if (j >= subWord.length() -1 ) {
mainWord = MainWord2;
break;
}
}
if (r > MainWord2.length()) {
MainWord2 = mainWord;
break;
}
}
}
System.out.println(mainWord);
}
}
Honestly I am stucked maybe there is an easier way to solve this. The main thing is that when I write a case like : "super 2 pe surr" At the end at "surr" the two StringBuilders start to act as one when I delete chatAt at one of them the other one changes also
No need to make it so complex.
String input = // complete user input
String[] words = String.split(input);
String mainWord = words[0];
int numWords = Integer.parseInt(words[1]); // this variable isn't needed
for(int i = 2; i < words.length; i++) {
if (mainWord contains words[i]) {
mainWord = mainWord.replace(words[i], ""); // remove subword from mainword
}
}
At the end, mainWord will be the original mainWord without any subwords that were entered later.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
String[] words = new String[n];
for (int i = 0; i <n ; i++) {
words[i] = in.nextLine();
}
String mainWord = words[0];
for (int i = 1; i <words.length ; i++) {
if (mainWord.contains(words[i])){
mainWord = mainWord.replace(words[i], "");
}
}
System.out.println(mainWord);
}
}
Here but the thing is if the letters are not one next to another it doesnt remove the subword.
I am trying to run a loop to see if an int is sorted. however the int has to be converted from a string. here is my code.
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{
}
}
}
}
when I run it, I get an error :
Exception in thread "main" java.lang.NumberFormatException: null
0149 at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
why does Integer.parseInt() not work
Your problem is that digits[a+1] hasn't been defined yet. I see that on line 2 you have
digits[a] = Character.toString(sq.charAt(a));
and you're iterating over a in a for loop, so I daresay that digits[a+1] hasn't been assigned yet.
UPDATE 1
Check out this solution, it shows how to properly catch that exception and how to avoid it:
Java: Good way to encapsulate Integer.parseInt()
UPDATE 2
I decided to add a fixed version of your code:
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1 || a == 0){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{
}
}
}
}
While I don't know the utility of your code, but this implementation might be simpler:
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
long sq = i*i;
if(sq > 9){
String[] digits = sq.toString().split("");
//Notice that I start at index 1, so I can do [a-1] safely
for(int a = 1; a < digits.length; a++){
if(Integer.parseInt(digits [a-1]) < Integer.parseInt(digits[a])){
System.out.print(sq);
//I guess we don't want a number like 169 (13*13) to be displayed twice, so:
break;
}
}
} else {
System.out.print(sq);
}
}
}
This is what I want :
Let the user enter as many numbers as they want until a non number is entered (you may
assume there will be less than 100 numbers). Find the most frequently entered number. (If
there are more than one, print all of them.)
Example output:
Input: 5
Input: 4
Input: 9
Input: 9
Input: 4
Input: 1
Input: a
Most common: 4, 9
I have got to the point in my code where I have managed to find out which are the most common numbers. However, I don't want to print out the same number over and over again; example from above: Most common: 4, 9, 9, 4
What needs to be done?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[100];
System.out.print("Input: ");
input[0] = in.readLine();
int size = 0;
for (int i = 1; i < 100 && isNumeric(input[i-1]); i++) {
System.out.print("Input: ");
input[i] = in.readLine();
size = size + 1;
}
/*for (int i = 0; i < size; i++) { //testing
System.out.println(input[i]);
}*/
int numOccur;
int[] occur = new int[size];
for(int i = 0; i < size; i++) {
numOccur = 0;
for (int j = 0; j < size; j++) {
if(input[i].equals(input[j])) {
numOccur = numOccur + 1;
}
}
occur[i] = numOccur;
//System.out.println(numOccur); //testing
}
int maxOccur = 0;
for(int i = 0; i < size; i++) {
if(occur[i] > maxOccur) {
maxOccur = occur[i];
}
}
//System.out.println(maxOccur); //testing
for (int i = 0; i < size && !numFound; i++) {
if(occur[i] == maxOccur) {
System.out.println(input[i]);
}
}
}
//checks if s is an in, true if it is an int
public static boolean isNumeric (String s) {
try {
Integer.parseInt(s);
return true; //parse was successful
} catch (NumberFormatException nfe) {
return false;
}
}
Found the solution!
String[] mostCommon = new String[size];
int numMostCommon = 0;
boolean numFound = false;
for (int i = 0; i < size; i++) {
int isDifferent = 0;
if (occur[i] == maxOccur) {
for (int j = 0; j < size; j++) {
if (!(input[i].equals(mostCommon[j]))) {
isDifferent = isDifferent + 1;
}
}
if (isDifferent == size) {
mostCommon[numMostCommon] = input[i];
numMostCommon = numMostCommon + 1;
}
}
}
for (int i = 0; i < numMostCommon - 1; i++) {
System.out.print("Most common: " + mostCommon[i] + ", ");
}
System.out.println(mostCommon[numMostCommon - 1]);
you could use the hash table for this to store the frequenceis as the limit is very less i.e. less than 100.
pseudo code would be like:
vector<int> hash(101)
cin>>input
if(isnumeric(input))
hash[input]++
else{
max=max_element(hash.begin(),hash.end());
for(int i=0;i<100;i++)
if(hash[i]==max)
print i
}
Set<Integer> uniqueMaxOccur = new HashSet<Integer>();
for (int i = 0; i < size ; i++) {
if(occur[i] == maxOccur) {
//System.out.println(input[i]);
uniqueMaxOccur.add(input[i]);
}
}
and display the values in the set
You can use a Set and store the values already printed.
What about something like this?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<string,int> numberLookup = new HashMap<string,int>();
Boolean doContinue = true;
while (doContinue)
{
System.out.print("Input: ");
String input = in.readLine();
if (isNumeric(input))
{
if (!numberLookup.containsKey(input))
numberLookup.put(input,1);
else
numberLookup.put(input, numberLookup.get(input) + 1);
}
else
doContinue = false;
}
maxOccur = numberLookup.values().max();
System.out.print("These numbers were all entered " + maxOccur + " times:");
Iterator it = numberLookup.entrySet().iterator();
while (it.hasNext())
{
(Map.Entry)it.next();
System.out.println(pairs.getKey());
}
}
Sorry, I'm a C# person and don't have a Java compiler on me, so this might need some tweaking.