I need to determine if a random number is unique - arrays

I need to write a function that receives the number generated in fillArray and determine if it has already been generated. I need to return a true or false thus determining if the random number must be put into the array.
Here's what I am working on. Thanks for any help. I've searched for anything similar but unfortunately cannot find anything.
public class RandomGenerator {
int Arr[] = new int[6];
int size;
public void fillArray() {
int randNum = (int) (Math.random() * 49) + 1;
for (int i = 0; i < size; i++) {
Arr[i] = randNum;
alreadyThere(randNum);
}
size++;
}
public int alreadyThere(int randNum) {
int find = randNum;
boolean found = false;
int i = 0;
while (!found && i < size) {
if (Arr[i] == find) {
found = true;
}
i++;
}
if (!found) {
}
return randNum;
}

Related

CS50 tideman struggling

I'm new to this site and I have been trying to do Tideman of the problem set 3 of CS50 course and have been struggling to this problem for days, please help me find the logical error in my code but please don't post the solution. Any help would be much appreciated. Thanks in advance
// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
int compare[MAX * (MAX - 1)];
int locked_count = 0;
for (int n=0; n < pair_count; n++)
{
circle_check(pairs[n], compare, 0, locked_count);
if(circle_check_out != 0)
{
locked[pairs[n].winner][pairs[n].loser]=true;
locked_count++;
}
}
return;
}
// Check wether circle
void circle_check( pair check, int compare[], int comp_numb, int locked_count)
{
if (compare[comp_numb+1] == compare[0] && comp_numb == locked_count)
{
circle_check_out = 0;
return;
}
else if (compare[comp_numb+1] != compare[0] && comp_numb == locked_count && comp_numb != 0)
{
circle_check_out = 1;
return;
}
for (int n=0; n < locked_count; n++)
{
if (locked[pairs[n].winner][check.winner] == true)
{
circle_check(pairs[n], compare, comp_numb+1, locked_count);
compare[comp_numb] = check.loser;
compare[comp_numb+1] = check.winner;
}
}
}
// Print the winner of the election
void print_winner(void)
{
bool dominate=true;
for (int win=0; win < candidate_count; win++)
{
for (int lose=0; lose < candidate_count; lose++)
{
if(locked[lose][win]==true)
dominate=false;
}
if (dominate==true)
printf("%s",candidates[win]);
}
return;
}

CS50 Runoff program is working but check50 says it doesn't

So basically my program is supposed to make some sort of a runoff election( Here you can see what is it: https://cs50.harvard.edu/x/2020/psets/3/runoff/). I needed to implement 6 functions in order to do it and I did it. My program works perfectly fine but check50 says that function print_winner doesn't work ( though it only costs 4/24 possible points). This function must print the candidate of an election if he has a majority of all votes (>50%). The error says just "print_winner must print name when someone has a majority, print_winner did not print winner of election" and 3 more of such errors.
Here is the whole code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cs50.h>
#include <math.h>
#define MAX 9
typedef struct
{
string name;
int votes;
bool eliminated;
}
candidate;
candidate candidates[MAX];
int voter_count;
int candidate_count;
int preferences[MAX][MAX];
float winner_vote;
//void check_preference(void);
bool is_tie(int min);
bool vote(int voter, int rank, string name);
bool print_winner(void);
void tabulate(void);
int find_min(void);
void eliminate(int min);
int main(int argc, string argv[])
{
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", MAX);
return 2;
}
for (int i = 0; i < candidate_count ; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
candidates[i].eliminated = false;
}
voter_count = get_int("Number of voters: ");
winner_vote = voter_count / 2;
int integer = winner_vote;
if (winner_vote == integer)
{
winner_vote++;
}
else
{
winner_vote = ceil(winner_vote);
}
for (int i = 0; i < voter_count; i++)
{
for (int j = 0; j < candidate_count; j++)
{
string name = get_string("Rank %i ", j + 1);
if (!vote(i, j, name))
{
printf("Invalid vote\n");
j--;
}
}
printf("\n");
}
//check_preference();
while (true)
{
tabulate();
if (print_winner())
{
return 1;
}
else if (is_tie(find_min()))
{
return 1;
}
else
{
eliminate(find_min());
}
}
}
void eliminate(int min)
{
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].eliminated)
{
continue;
}
else if (min == candidates[i].votes)
{
candidates[i].eliminated = true;
}
}
}
int find_min(void)
{
int min = MAX;
for (int i = 1; i < candidate_count; i++)
{
if (candidates[i].eliminated)
{
continue;
}
else if (min > candidates[i].votes)
{
min = candidates[i].votes;
}
}
return min;
}
bool is_tie(int min)
{
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].eliminated)
{
continue;
}
else if (min == candidates[i].votes)
{
continue;
}
else
{
return 0;
}
}
return 1;
}
bool vote(int voter, int rank, string name)
{
bool exist = false;
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(name, candidates[preferences[voter][i]].name) == 0 && rank > 0)
{
return 0;
}
if (strcmp(name, candidates[i].name) == 0)
{
preferences[voter][rank] = i;
exist = true;
break;
}
}
return exist;
}
bool print_winner(void)
{
// candidate candidateHolder;
for (int f = 0; f < candidate_count; f++)
{
//candidateHolder = candidates[f];
if (candidates[f].votes >= winner_vote)
{
printf("%s\n", candidates[f].name);
return 1;
}
}
return 0;
}
void tabulate(void)
{
int check = 0;
for (int i = 0; i < voter_count; i++)
{
if (!candidates[preferences[i][check]].eliminated)
{
candidates[preferences[i][check]].votes++;
check = 0;
}
else
{
check++;
i--;
}
}
}
Here is the function that creates error:
bool print_winner(void)
{
// candidate candidateHolder;
for (int f = 0; f < candidate_count; f++)
{
//candidateHolder = candidates[f];
if (candidates[f].votes >= winner_vote)
{
printf("%s\n", candidates[f].name);
return 1;
}
}
return 0;
}
looks like you forgot
"If any candidate has a majority (more than 50%) of the first preference votes, that candidate is declared the winner of the election."
The variables that are used to determine winner_vote (aka) the majority have to be floats i.e voter_count / 2. Integers will not work if you have to divide 3/2 or 5/2
Additionally, in order to win the majority, the candidates[f].votes has to be > the majority, not >=. In the latter instance a tie between two candidates would be printed in the print_winner function. Ties are determined in the is_tie function later in the code.
Bool functions must have a return value of true or false.
The problem here is that your printer_winner will return a 0 or a 1.
check50 expects a TRUE or FALSE.
a simple statement will fix that for you:
printf("%s", winner_vote ? "true" : "false");
This will convert the 1 and 0 to TRUE ans FALSE.
Hope this helps. First time programmer here ;).
I declared winner_vote in the function and it worked
The problem is it puts my function inside of their code. So winner_vote variable is undefined there. There's nothing to do with 1 or 0. By the way, 1 in a bool means true and 0 means false. Why I put them instead of words because the explanation video said return 1 if ... and return 0 if ... I thought maybe this will change something.
And my other problem was that i forgot to mark my answer as a correct one. So people are still trying to help
You could init two global variables one integer, other floating(int max;
float pmax;) and delete your unnecessary code and variables in the beginning.
Below your function content:
bool print_winner(void)
{
for (int i = 0; i < candidate_count; i++)
{
if (max < candidates[i].votes)
{
max = candidates[i].votes;
pmax = ((float) max /(float) voter_count);
if (pmax > 0.5)
{
printf("%s\n", candidates[i].name);
return true;
}
}
}
return false;
}
bool print_winner(void)
{
int maj = voter_count / 2;
for (int i = 0; i < candidate_count; i++)
{
if (candidates[i].votes > maj)
{
printf("%s\n",candidates[i].name);
return true;
}
}
return false;
}
Why don't you try this instead??
Why do you return an int when type specified is bool?
you can use this as an alternative as well
bool won = print_winner();
if (won)
{
break;
}
// Eliminate last-place candidates
int min = find_min();
bool tie = is_tie(min);
// If tie, everyone wins
if (tie)
{
for (int i = 0; i < candidate_count; i++)
{
if (!candidates[i].eliminated)
{
printf("%s\n", candidates[i].name);
}
}
break;
}
// Print the winner of the election, if there is one
bool print_winner(void)
{
int won;
win_score = voter_count / 2;
won = win_score;
if (win_score == won)
{
win_score++;
}
else
{
win_score = ceil(win_score);
}
// for each candidate sum the 1st choices
// if candidates[i].votes > voters / 2; win then quit
// else call find_min then is_tie if so everyone wins else eliminate min
// then tabulate next rank to candidate/s
for (int j = 0; j < candidate_count; j++)
{
if (candidates[j].votes >= win_score)
{
printf("%s\n", candidates[j].name);
return 1;
}
}
return 0;
}

exception in thread main java.lang.arrayindexoutofboundsexception 1

well i have to make a java program which determinate if a given number is capicua(131,12121,13431) the same number from last to initial digit. but it gives me the error, in the line 23 (while(i>=0).....) the question is how can i call the array into thath while. pls help me im really sad :c. Here is the code:
public class Capi {
/**
*
**/
public static int num(int a) { // counting digits from the number
int n = 0;
while(a>=10) { a = a/10;
n = n+1;
}
return n;
}
public static boolean det(int a, int n) {
int z = a;
double y =0;
n = n-1;
int i = 0;
int x[] = new int[n];
for(i=0; i<x.length; i++) { // saving the digits into x[i]
x[i] = a%10;
a = a/10;
}
while(i>=0) { y = x[i]*Math.pow(10,n-1); // calling the digits x[i],x[i-1] untill it gets 0
i = i - 1;
n = n -1;
}
double num1= y + a*Math.pow(10,n);
if(num1 == z) { return true; }
else { return false; }
}
}
I feel the issue is that the value of i is set to x.length, before you attempt while(i>=0). I have hence added i-- before you run the loop.
See if the following does the trick.
public class Capi {
public static int num(int a) { // counting digits from the number
int n = 0;
while(a>=10) {
a = a/10;
n = n+1;
}
return n;
}
public static boolean det(int a, int n) {
int z = a;
double y = 0;
n = n-1;
int i = 0;
int x[] = new int[n];
for(i=0; i<x.length; i++) { // saving the digits into x[i]
x[i] = a%10;
a = a/10;
}
//i is now set to x.length, thus decrement it as index runs from 0 to x.length-1
i=i-1;
while(i>=0) {
y = x[i]*Math.pow(10,n-1); // calling the digits x[i],x[i-1] untill it gets 0
i = i - 1;
n = n -1;
}
double num1= y + a*Math.pow(10,n);
if(num1 == z) {
return true;
}
else {
return false;
}
}
}

Array index out of bounds in sieve of eratosthenes

I am having trouble with ArrayIndexOutOfBounds.
I am new to coding and I don't fully understand this problem and I am unable to fix it. Any help is appreciated.
public class Primes {
public static void main(String[] args) {
final int SIZE = 10000;
boolean[] numberIsPrime = new boolean[SIZE];
int rowCounter = 0;
for( int index = 1; index <= SIZE; index++) {
numberIsPrime[index] = true;
}
for( int index = 2; index <= SIZE; index++) {
if( numberIsPrime[index] = true){
for( int i = index; i <= SIZE; i++){
numberIsPrime[index * i] = false;
}
}
}
for( int index = 1; index <= SIZE; index++){
if( numberIsPrime[index] = true){
System.out.println(index + " ");
rowCounter++;
if( rowCounter == 10){
System.out.println();
}
}
}
}
}
You should tag the question with the language you're using, but I'm gonna assume it's Java. The problem is
boolean[] numberIsPrime = new boolean[SIZE];
...
for( int index = 1; index <= SIZE; index++) {
numberIsPrime[index] = true;
}
The first line declares numberIsPrime as an array of size 10000. That means you can access numberIsPrime[0], numberIsPrime[1], ... numberIsPrime[9999]. You can't access numberIsPrime[10000].

TicTacToe Array. Winner method and is square free

I dont know what I'm doing wrong here.
Can anyone tell me what's wrong with my checkRow code in checkWinner and isSquareFree method?
Here's my code:
public class TicTacToe
{
/**
* intance variables to hold the data's state for the game.
*/
public static final int GRIDSIZE = 3;
public static final char BLANK = ' ';
public static final char TIE = 'T';
public static final char NOUGHT = 'O';
public static final char CROSS = 'X';
private char[][] grid;
private char WhoseTurn;
/**
* Construct a tic tac toe grid ready to play a new game.
* The game grid should be GRIDSIZE by GRIDSIZE spaces
* all containing the BLANK character.
* Initially, the starting player is not decided,
* indicated by setting whoseturn as BLANK.
*/
public TicTacToe()
{
this.WhoseTurn = BLANK;
this.grid = new char[GRIDSIZE][GRIDSIZE];
for (int r = 0; r < grid.length; r++)
{
for ( int c = 0; c < grid[r].length; c++)
{
this.grid[r][c] = BLANK;
}
}
}
/**
* Reset the tic tac toe game ready to play again.
* Conditions for play are the same as for the constructor.
*/
public void newGame()
{
char[][] boardToClear = getGrid();
final int sizeOfBoard = grid.length;
for ( int row = 0; row < grid.length; row++)
{
for ( int col = 0; col < grid.length; col++)
{
grid[row][col] = BLANK;
}
}
}
public char[][] getGrid()
{
int gridLen = grid.length;
char[][] gridCopy = new char[gridLen][];
for ( int r = 0; r < gridCopy.length; r++)
{
gridCopy[r] = new char[gridCopy.length];
for ( int c = 0; c < gridCopy.length; c++)
{
gridCopy[r][c] = grid[r][c];
}
}
return gridCopy;
}
public char getWhoseTurn()
{
return WhoseTurn;
}
/**
* printGrid() displays the current state of the game grid
* on the console for debugging.
* It uses the form feed character \u000C to clear the console before
* printing the current grid.
*/
private void printGrid()
{
System.out.print('\u000C'); // clear the console window
for (int x = 0; x < GRIDSIZE-1; x++) {
System.out.print(grid[x][0] + "|" +
grid[x][1] + "|" + grid[x][2]);
System.out.println("\n-----"); //
System.out.print(grid[GRIDSIZE-1][0] + "|" +
grid[GRIDSIZE-1][1] + "|" +
grid[GRIDSIZE-1][2]);
}
}
// Now print last row (with no bottom edge)
private boolean checkIfGridFull()
{
char[][] board = getGrid();
int size = grid.length;
for ( int row = 0; row < size; row++)
{
for ( int col = 0; col < board[row].length; col++)
{
if ( grid[row][col] == BLANK)
{
return false;
}
}
}
return true;
}
public boolean move(char player, int row, int col)
{
char[][] boardToPlay = getGrid();
int size = grid.length;
char x = player;
if ( (player == NOUGHT) || ( player == CROSS))
{
if ( (x == WhoseTurn) || (WhoseTurn == BLANK))
{
if ((checkIfGridFull() == false) && ( boardToPlay[row][col] == BLANK))
{
if( (row < size) && ( col < size))
{
boardToPlay[row][col] = player;
if ( player == CROSS)
{
WhoseTurn = NOUGHT;
}
if ( player == NOUGHT)
{
WhoseTurn = CROSS;
}
return true;
}
}
}
}
return false;
}
public boolean isSquareFree( int row, int col)
{
if ((grid[row][col] == BLANK))
{
return true;
}
return false
;
}
public char checkWinner()
{
int countNought;
int countCross ;
int size = grid.length;
for ( int row = 0; row < size; row++)
{
countNought = 0;
countCross = 0;
for ( int col = 0; col < size; col++)
{
if ( grid[row][col] == CROSS)
{
countCross++;
}
if ( grid[row][col] == NOUGHT)
{
countNought++;
}
if ( countNought == size)
{
return NOUGHT;
}
if ( countCross == size)
{
return CROSS;
}
}
}
return BLANK;
}
}
One good method for tracking down a bug in a project like this is to use print line statements. Try this: put a print line somewhere near where you think the problem is, and print out the values of some of the local variables. If you see values that you shouldn't then you know that your data has come into some trouble earlier on in the code. In that case, move the print lines further back in the flow and try again. Keep doing this until you notice values going from good to bad (or bad to good): at that point you have tracked down the code that contains the bug.
Once you've done this, you will usually have only a small function to think about, and it will be much easier to understand what you've done wrong. If you still can't find the problem, then post the code snippet here and someone will probably be able to help you.
checkWinner() is wrong you're not checking diagonals, just write the eights winning combinations

Resources