In my Ruby class, I'm building a Connect Four game that my professor will run in command prompt.
It has to be done with a double array and while loops, and no break/exit/abort, loop do, classes, instance, or global variables.
My grid array is made up of 64 '.' placeholders in a nested array. I am trying to start at the bottom row of my 8x8 grid, and drop in a player's piece: 'X' or '0'.
I'm not sure how to move upward from row 8/index 7 to row 7/index 6 if the bottom row of a column has already been taken. Do I use if or case statements? Do I decrement the row? I have tried putting in if/elsif, but I got nowhere.
def print_playing_grid (playing_board)
puts "1 2 3 4 5 6 7 8"
playing_board.each do |row|
puts row.join(" ")
end
end
print_playing_grid(grid_array)
# this 'win'/while is only here for testing so the board will repeat on screen
win = false
while win == false
puts
puts "Please select a column to make your move (Player X):"
user_choice = gets.to_i
row = 7
column = user_choice - 1
while row < grid_array.size
grid_array[row][column] = 'X'
row += 1
end
puts
print_playing_grid(grid_array)
end
As it's only two conditions (cell is occupied or not) I'd be more likely to use an if rather than a case... I would use case for multiple tests as it can be a little cleaner than if and elsif.
player_token = 'X'
row = grid_array.size - 1
column = user_choice - 1
while (grid_array.size - row) <= grid_array.size
if grid_array[row][column] == '.'
grid_array[row][column] = player_token
row = -1 # (to exit the while loop)
else
row -= 1
end
end
for an example of where I'd consider using a case...
player_token = 'X'
row = grid_array.size - 1
column = user_choice - 1
dropping_a_token = true
while dropping_a_token
case
when row < 0
dropping_a_token = false
when grid_array[row][column] == '.'
grid_array[row][column] = player_token
dropping_a_token = false
else
row -= 1
end
end
Related
I am trying to create password Generate in ruby. At the moment all is working just got stuck at the final piece of generating the password.
I asked user if he/she would like the password to include numbers, lowercase or uppercase.
If YES, user will enter 1 and 0 for NO.
I used the code below to generate password if everything is 1. Meaning user want to include numbers, lowercase and uppercase.
if numbers == 1 && lowercase == 1 && uppercase == 1
passGen = [(0..9).to_a + ('A'..'Z').to_a + ('a'..'z').to_a].flatten.sample(10)
end
p passGen
This works 90% of the time. 10% of the time the generated password will not include say any numbers. But everything else present. I am not sure if this is because of the size or length of Array from which the password is sampled.
Anyway lets go to the main problem below
Here is the problem, I am struggling to write the code to generate password if one or more of input is 0. That's if user don't want to include numbers. Or no numbers and uppercase etc . As I can't predict what user may want or not want. I need help on this please.
Thank you.
You will need to make your input array more dynamic:
passGen = []
passGen += (0..9).to_a if numbers == 1
passGen += ('A'..'Z').to_a if uppercase == 1
passGen += ('a'..'z').to_a if lowercase == 1
passGen.sample(10).join
Now, to tackle your other issue with missing characters - this is caused as you are simply taking 10 random characters from an array. So it can just take, for example, all digits.
To tackle this you need to get one character from each generator first and then generate the remaining characters randomly and shuffle the result:
def generators(numbers:, lowercase:, uppercase:)
[
(0..9 if numbers),
('A'..'Z' if uppercase),
('a'..'z' if lowercase)
].compact.map(&:to_a)
end
def generate_password(generators:, length:, min_per_generator: 1)
chars = generators.flat_map {|g| Array.new(min_per_generator) { g.sample }}
chars += Array.new(length - chars.length) { generators.sample.sample }
chars.shuffle.join
end
gens = generators(numbers: numbers == 1, uppercase == 1, lowercase: lowercase == 1)
Array.new(10) { generate_password(generators: gens, length: 10) }
The code doesn't know it needs to include a digit/letter from every group. The sample takes random signs and since you a basically sampling 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz there is a possibility that all the signs will not be digits.
The easiest way to fix it is to check if a sign from every group is in the "password" and then replace a random sign with a sign from group that is not present.
If I were to program this I would do it like that
def random_from_range(range)
range.to_a.sample.to_s
end
def passGen(numbers, lowercase, uppercase)
result = ''
possibleSigns = []
if numbers == 1
range = (0..9)
result += random_from_range(range)
possibleSigns += range.to_a
end
if lowercase == 1
range = ('A'..'Z')
result += random_from_range(range)
possibleSigns += range.to_a
end
if uppercase == 1
range = ('a'..'z')
result += random_from_range(range)
possibleSigns += range.to_a
end
desired_lenth = 10
while result.length < desired_lenth
result += possibleSigns.sample.to_s
end
result
end
puts passGen(1,1,1)
By saying (0..9).to_a + ('A'..'Z').to_a + ('a'..'z').to_a, you're creating an Array of 10 + 26 + 26 = 62 elements, and then you pick only 10 elements out of it.
At your place I'd wrap password generation around an until block:
def generate_password_with_digits_and_caps
[(0..9).to_a + ('A'..'Z').to_a + ('a'..'z').to_a].flatten.sample(10).join
end
passGen = ''
until passGen.match(/[A-Z]/) && passGen.match(/[a-z]/) && passGen.match(/\d/)
passGen = generate_password_with_digits_and_caps
end
This could also work (closer to your snipppet):
if numbers == 1 && lowercase == 1 && uppercase == 1
passGen = ''
until passGen.match(/[A-Z]/) && passGen.match(/[a-z]/) && passGen.match(/\d/)
passGen = [(0..9).to_a + ('A'..'Z').to_a + ('a'..'z').to_a].flatten.sample(10).join
end
end
Start with something simple and stupid:
passGen = (('0'..'9').to_a.sample(1)+ ('A'..'Z').to_a.sample(1)+('a'..'z').to_a.sample(8).shuffle).join
Technically speaking, this already fulfills your requirement. From the viewpoint of aesthetics and security, the disadvantage here is that the number of upper case characters is always 8. A more elegant solution would be to find three non-zero integers which add up to 10, and can be used as the arguments for the sample call. Also, if no numbers are requested, you simply pass 0 as argument to sample.
Since this exceeds the scope of your question, and I don't even know whether you want to go so far, I don't elaborate on this here further.
I am trying to make a game and i have a 2d array
So its like this:
Grid[x][y]
lets pretend these values are in it:
Column 1 Column 2 Column 3 Column 4 Column 5
1 2 5 2 5
2 2 3 1 1
1 4 3 4 5
1 3 3 3 5 <-- match this row
3 5 3 4 5
2 4 3 4 5
2 4 4 4 5
In the middle (index 4) i want to check if there are at least 3 times the same number and what about if there are 4 times the same or even 5.
How do you check this ? What would be a good way to find the same and delete those that are the same... I am stuck to figure out the logic to make something like this
this is what i tried:
grid = {}
for x = 1, 5 do
grid[x] = {finish = false}
for y = 1, 7 do
grid[x][y] = {key= math.random(1,4)}
end
end
function check(t)
local tmpArray = {}
local object
for i = 1,5 do
object = t[i][1].key
if object == t[i+1][1].key then
table.insert( tmpArray, object )
else
break
end
end
end
print_r(grid)
check(grid)
print_r(grid)
where print_r prints the grid:
function print_r ( t )
local print_r_cache={}
local function sub_print_r(t,indent)
if (print_r_cache[tostring(t)]) then
print(indent.."*"..tostring(t))
else
print_r_cache[tostring(t)]=true
if (type(t)=="table") then
for pos,val in pairs(t) do
if (type(val)=="table") then
print(indent.."["..pos.."] => "..tostring(t).." {")
sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
print(indent..string.rep(" ",string.len(pos)+6).."}")
else
print(indent.."["..pos.."] => "..tostring(val))
end
end
else
print(indent..tostring(t))
end
end
end
sub_print_r(t," ")
end
It doesnt work that great because i check with the index after that one and if that isnt the same it doesnt add the last one..
I dont know if it is the best way to go...
If i "delete" the matched indexes my plan is to move the index row above or beneath it into the 4 index row... but first things first
You should compare the second index not the first: in the table
g = {{1,2,3}, {4,5,6}}
g[1] is first row i.e. {1,2,3}, not {1,4} the first column (first element of first and second rows). You were doing same thing in previous post of yours, you should reread the Lua docs about tables. You should do something like
for i = 1,#t do
object = t[i][1].key
if object == t[i][2].key then
This will only compare first two items in row. If you want to check whether the row has any identical consecutive items you will have to loop over the second index from 1 to #t[i]-1.
You might find the following print function much more useful, as it prints table as a grid, easier to see before/after:
function printGrid(g)
for i, t in ipairs(g) do
print('{' .. table.concat(t, ',') .. '}')
end
end
I have an array with a set of chronological serial numbers and another source array with random serial numbers associated with a numeric value. The code creates a new cell array in MATLAB with the perfectly chronological serial numbers in one column and in the next column it inserts the associated numeric value if the serial numbers match in both original source arrays. If they don't the code simply copies the previous associated value until there is a new match.
j = 1;
A = {random{1:end,1}};
B = cell2mat(A);
value = random{1,2};
data = cell(length(serial), 1);
data(:,1) = serial(:,1);
h = waitbar(0,'Please Wait...');
steps = length(serial);
for k = 1:length(serial)
[row1, col1, vec1] = find(B == serial{k,1});
tf1 = isempty(vec1);
if (tf1 == 0)
prices = random{col1,2};
data(j,2) = num2cell(value);
j = j + 1;
else
data(j,2) = num2cell(value);
j = j + 1;
end
waitbar(k/steps,h,['Please Wait... ' num2str(k/steps*100) ' %'])
end
close(h);
Right now, the run-time for the code is approximately 4 hours. I would like to make this code run faster. Please suggest any methods to do so.
UPDATE
source input (serial)
1
2
3
4
5
6
7
source input (random)
1 100
2 105
4 106
7 107
desired output (data)
SR No Value
1 100
2 105
3 105
4 106
5 106
6 106
7 107
Firstly, run the MATLAB profiler (see 'doc profile') and see where the bulk of the execution time is occuring.
Secondly, don't update the waitbar on every iteration> Particularly if serial contains a large (> 100) number of elements.
Do something like:
if (mod(k, 100)==0) % update on every 100th iteration
waitbar(k/steps,h,['Please Wait... ' num2str(k/steps*100) ' %'])
end
Some points:
Firstly it would help a lot if you gave us some sample input and output data.
Why do you initialize data as one column and then fill it's second in the loop? Rather initialize it as 2 columns upfront: data = cell(length(serial), 2);
Is j ever different from k, they look identical to me and you could just drop both the j = j + 1 lines.
tf1 = isempty(vec1); if (tf1 == 0)... is the same as the single line: if (!isempty(vec1)) or even better if(isempty(vec1)) and then swap the code from your else and your if.
But I think you can probably find a fast vecotrized solution if you provide some (short) sample input and output data.
I realized a flaw on my coding for picking cards from my structure group arrays this morning for a tabletop card game I'm converting to computer.
Currently the code is set up to randomly pick an array of a specific card, but if quantity of cards in the group is < 1, then the group is skipped. For my deck this isn't being truly random because each card has its own quantity. Some cards have 10 cards, others 6, most 4. How can I code it to where it looks at all these quantity numbers as a whole and picks a random card out of these numbers.
If GameSize >= 3 Then
For StartHands = 10 To 14
Number = (DeckGroup(Rnd.Next(0, DeckGroup.Count)).ID)
'Cardslots Player3
If CardTypeArray(StartHands) = "" Then
If DeckGroup(Number).QuantityInteger > 0 Then
DeckGroup(Number).QuantityInteger -= 1
Player1HandGroup(Number).QuantityInteger3 += 1
CardTypeArray(StartHands) = Player1HandGroup(Number).CardType
Me.NumberArray(StartHands) = Number
Else
'Recall Procedure if Generated Random Number is not allowed
'due to QuantityInteger <= 0
Call StartButton_Click(sender, e)
End If
End If
Next StartHands
End If
when playing a card, and drawing a new card, I use this coding scheme, to prevent stackoverflow, but is virtual the same.
Dim temp As IEnumerable(Of LunchMoneyGame.LunchMoneyMainForm.Group) = From r In DeckGroup Where r.QuantityInteger > 0 Select r
If temp IsNot Nothing AndAlso temp.count > 0 Then
Number = (temp(Rnd.Next(0, temp.Count)).ID)
DeckGroup(Number).QuantityInteger -= 1
'Select the Player depending value of T
Select Case T
Case 0
Player1HandGroup(Number).QuantityInteger += 1
Case 1
Player1HandGroup(Number).QuantityInteger2 += 1
Case 2
Player1HandGroup(Number).QuantityInteger3 += 1
Case 3
Player1HandGroup(Number).QuantityInteger4 += 1
Case 4
Player1HandGroup(Number).QuantityInteger5 += 1
End Select
Edit:
Improved question:
How can I weight the probably of drawing a card based on how many of a particular card are left in the decks quantity integer for each card?
The idea of my solution is to generate a random number over the total number of availables cards in all deck groups. Finally we find the deck group this number targets within a loop:
Dim totalNumerOfCards As Integer = DeckGroup.Sum(Function(d) d.QuantityInteger)
Dim Number As Integer = Rnd.Next(totalNumerOfCards)
Dim numCards As Integer = 0
Dim groupIndex As Integer = 0
Dim cardIndex As Integer = 0
Dim i As Integer = 0
While i < DeckGroup.Length AndAlso numCards <= Number
groupIndex = i
cardIndex = Number - numCards
numCards += DeckGroup(i).QuantityInteger
i += 1
End While
Console.WriteLine("Your card is in DeckGroup({0}), card index {1}",
groupIndex, cardIndex);
I am trying to program a noise reduction algorithm that works with a set of datapoints in a VB.NET DataTable after being helped with my other question. Basically, I want to take two integers, a coordinate value (yCoord for example) and a threshold smoothing value (NoiseThresh), and take the average of the values in the range of (yCoord - NoiseThresh, yCoord + NoiseThresh) and store that number into an array. I'd repeat that process for each column (in this example) and end up with a one-dimensional array of average values. My questions are:
1) Did anything I just say make any sense ;), and
2) Can anyone help me with the code? I've got very little experience working with databases.
Thanks!
An example of what I'm trying to do:
//My data (pretend it's a database)
1 4 4 9 2 //yCoord would equal 5
6 3 8 12 3 //yCoord = 4
8 3 -2 2 0 //yCoord = 3
9 17 3 7 5 //yCoord = 2
4 1 0 9 7 //yCoord = 1
//In this example, my yCoord will equal 3 and NoiseThresh = 1
//For the first column
Array(column1) = //average of the set of numbers centered at yCoord = 3 _
//(in this case 8) and the NoiseThresh=1 number on either side (here 6 & 9)
//For the second column
Array(column2) = //average of the numbers 3,3,17 for example
//etc., etc.,
This would be performed on a large data set (typical numbers would be yCoord=500, NoiseThresh = 50, Array length = 1092) so there is no possibility of manually entering the numbers.
I hope this helps clarify my question!
P.S.: yes, I know that // isn't a VB.NET comment.
I must admit that i've yet not understood the range part (NoiseThresh etc.), but this is a start:
Dim averages = (From col In tbl.Columns.Cast(Of DataColumn)()
Select tbl.AsEnumerable().
Average(Function(r) r.Field(Of Int32)(col.ColumnName))).
ToArray()
It calculates every average of each column in the DataTable and creates a Double() from the result (average can result in decimal places even if used on integers).
Edit: With your example i've now understood the range part. So basically yCord is the row-index(+1) and noiseThreas is the row-range (+/- n rows).
Then this gives you the correct result(made some code comments):
Dim yCord = 2 ' the row index(-1 since indices are 0-based) '
Dim noiseThresh = 1 ' +/- row '
' reverse all rows since your sample begins with index=5 and ends with index=1 '
Dim AVGs As Double() = (
From colIndex In Enumerable.Range(0, tbl.Columns.Count)
Select tbl.AsEnumerable().Reverse().
Where(Function(r, index) index >= yCord - noiseThresh _
AndAlso index <= yCord + noiseThresh).
Average(Function(r) r.Field(Of Int32)(colIndex))).ToArray()
The most important part of this this LINQ query is the Where. It applies your range on the IEnumerable(of DataRow). Then i'm calculating the average of these rows for every column. The last step is materializing the query to a Double().
Result:
(0) 7.666666666666667 Double => (6+8+9)/3
(1) 7.666666666666667 Double => (3+3+17)/3
(2) 3.0 Double => (8-2+3)/3
(3) 7.0 Double => (12+2+7)/3
(4) 2.6666666666666665 Double => (3+0+5)/3
Edit2:
One last thing. I assume that to do the same for the other axis I just
switch x & y and row & column?
It's not that simple. But have a look yourself:
Dim noiseThresh = 1 ' +/- column '
Dim xCord = 2 ' the column index(-1 since indices are 0-based) '
' assuming that your x-cords now start with index=0 and ends with tbl.Column.Count-1 '
Dim AVGs As Double() = (
From rowIndex In Enumerable.Range(0, tbl.Rows.Count)
Select tbl.Columns.Cast(Of DataColumn)().
Where(Function(c, colIndex) colIndex >= xCord - noiseThresh _
AndAlso colIndex <= xCord + noiseThresh).
Average(Function(c) tbl.Rows(rowIndex).Field(Of Int32)(c.Ordinal))).ToArray()
Result:
(0) 5.666666666666667 Double => (4+4+9)/3
(1) 7.666666666666667 Double => (3+8+12)/3
(2) 1.0 Double => (3-2+2)/3
(3) 9.0 Double => (17+3+7)/3
(4) 3.3333333333333335 Double => (1+0+9)/3