Inaccurate scanning of Bash array elements

 
Thread Tools Search this Thread
Top Forums UNIX for Beginners Questions & Answers Inaccurate scanning of Bash array elements
# 1  
Old 01-19-2017
Linux Inaccurate scanning of Bash array elements

Code:
username=cogiz
#!/bin/bash

shuffle() #@ USAGE: shuffle
{ #@ TODO: add options for multiple or partial decks
 Deck=$(
   printf "%s\n" {2,3,4,5,6,7,8,9,T,J,Q,K,A}{H,S,D,C} |
    awk '## Seed the random number generator
         BEGIN { srand() }

         ## Put a random number in front of each line
         { printf "%.0f\t%s\n", rand() * 99999, $0 }
    ' |
     sort -n |  ## Sort the lines numerically
      cut -f2  ## Remove the random numbers
  )
}

_deal() #@ USAGE: _deal [N] -- where N is no. of cards; defaults to 1
{       #@ RESULT: stored in $_DEAL
    local num=${1:-1}
    set -- $Deck
    _DEAL=${@:1:$num}
    shift "$num"
    cards_remaining=$#
    Deck=$*
}

deal() #@ USAGE: deal [N]
{      #@ RESULT: cards printed one to a line
    _deal "$@"
    printf "%s " $_DEAL
}

################################################

shuffle
declare -a PH
deal 8 > /home/cogiz/playerhand.txt           #  (7D 3H 4D 9H KC 2H 7C 9S)
deal 8 > /home/cogiz/computerhand.txt
deal 1 > /home/cogiz/activecard.txt            # (9C)
mapfile -t PH < /home/cogiz/playerhand.txt
X=$(</home/cogiz/activecard.txt)
A=( "${X[@]::1}" )                               # 9
B=( "${X[@]:1}" )                                # C
C=8                                                    # 8

for e in ${PH[@]}; do
  
   if [[ $e =~ $A|$B|8 ]]; then
      printf "$e " >> /home/cogiz/choices.txt
   else
      printf "0 " >> /home/cogiz/choices.txt
   fi
done

The above script is a rewrite of a terminal game of crazy 8's in Bash that I have been working on. The problem I am having is that the output file (choices.txt) is not showing me all of the results that it should. when the above script was run, the output in the choices.txt file was ( 0 0 0 9H 0 0 0 9S ).

It should have been ( 0 0 0 9H KC 0 7C 9S ).

Each time I run this script ( ./crazy.sh ) it gives me a different answer but always an incomplete one.

Can anyone explain to me why this is happening? I have been racking my brain for days trying to figure this out. Why does it show some valid card choices but not all? What am I missing?

Thank you in advance for any and all suggestions and advice.

Cogiz
# 2  
Old 01-19-2017
To start with:
Code:
username=cogiz
#!/bin/bash

should be:
Code:
#!/bin/bash
username=cogiz

try:

Code:
A=${X[@]::1}
B=${X[@]:1}

or:

Code:
read X < /home/cogiz/activecard.txt    # instead of X=$(</home/cogiz/activecard.txt)
A=${X%?}
B=${X#?}

Otherwise there are spurious spaces in the variables A and B that mess up things with the regex comparison...

Last edited by Scrutinizer; 01-19-2017 at 03:17 PM..
This User Gave Thanks to Scrutinizer For This Post:
# 3  
Old 01-19-2017
Running your final for loop with the variables (not arrays!) set to the values indicated, I get 0 0 0 9H KC 0 7C 9S, so the logics seem to be OK. The inconsistent behaviour might be caused by some creative use of variables, arrays, separators, and assignments.
The way you assign them, A and B will be arrays with one single element only. Scrutinizer already proposed an alternative use.
mapfile will (man bash) "Read lines from the standard input into the indexed array variable array", so again array PH has just one element as the input file has all cards in one line separated by spaces.
While the logics should work nevertheless, I can't assess the ramifications of using arrays vs. variables. Wouldn't it be worthwhile to try simple variables?


BTW, would your system allow for this construct:
Code:
Deck=$(shuf -e {2,3,4,5,6,7,8,9,T,J,Q,K,A}{H,S,D,C})


Last edited by RudiC; 01-19-2017 at 02:19 PM.. Reason: typo, small enhancement.
These 3 Users Gave Thanks to RudiC For This Post:
# 4  
Old 01-19-2017
inaccurate scanning of Bash array....SOLVED

Thank you very much for your suggestions. The following worked like a charm:

Code:
read X < /home/cogiz/activecard.txt
A=${X%?}
B=${X#?}
C=8

Now the scanning of ${PH[@]} for $A|$B|8 works perfectly.

Cogiz

---------- Post updated at 07:42 PM ---------- Previous update was at 07:21 PM ----------

This also worked like a charm:

Code:
Deck=$(shuf -e {2,3,4,5,6,7,8,9,T,J,Q,K,A}{H,S,D,C})

I like this much better....very streamlined, less complicated.

Thank you,

Cogiz

Last edited by Scrutinizer; 01-20-2017 at 04:18 AM..
# 5  
Old 01-20-2017
Well, talking of complexity: your entire script looks somewhat overcomplicated to me. Although I like subroutines and functions for repeating tasks, jumping to and fro between them just for the sake of it might overdo it. Consider the following - it should do exactly what you need (if I read the script correctly):
Code:
set -- $(shuf -e {2,3,4,5,6,7,8,9,T,J,Q,K,A}{H,S,D,C})
PH=$(echo ${@:1:8} | tee /home/cogiz/playerhand.txt); shift 8 
DU=$(echo ${@:1:8} | tee /home/cogiz/computerhand.txt); shift 8
XX=$(echo ${@:1:1} | tee /home/cogiz/activecard.txt); shift 1
for e in $PH
   do    if [[ $e =~ ${XX%?}|${XX#?}|8 ]]
           then  printf "$e "
           else  printf "0 "
         fi
   done
0 0 0 KS 8S 0 0 0
echo
echo $PH, $DU, $XX
5H QC QH KS 8S 9C 9D 3H, 6H 7S 7H 4H QS JH AD JS, AS

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Get unique elements from Array

I have an array code and output is below: echo $1 while read -r fline; do echo "%%%%%%$fline%%%%%" fmy_array+=("$fline") done <<< "$1" Output: CR30903 YU0007 SRIL CR30903 Yogesh SRIL %%%%%%CR30903 YU0007 SRIL%%%%% %%%%%%CR30903 Yogesh SRIL%%%%% ... (8 Replies)
Discussion started by: mohtashims
8 Replies

2. Shell Programming and Scripting

Array to array scanning

trying a little bit of array scanning for open ports. my code looks like below: /bin/netstat -lntp|\ awk 'BEGIN { split("25 80 2020 6033 6010",q); } $1 == "tcp" { split($4,a,":"); p]++; } $1 == "tcp6" { split($4,a,":");p]++ } END { for ( i in q ) { if (! q in p ) {... (8 Replies)
Discussion started by: busyboy
8 Replies

3. UNIX for Beginners Questions & Answers

Random choice of elements in bash array

example of problem: #!/bin/bash P=(2 4 7) How would you randomly choose one of these 3 numbers in this array? either 2 or 4 or 7 is needed...but only one of them. Thanks in advance Cogiz Please use CODE tags as required by forum rules! (3 Replies)
Discussion started by: cogiz
3 Replies

4. UNIX for Beginners Questions & Answers

Scanning array for partial elements in Bash Script

Example of problem: computerhand=(6H 2C JC QS 9D 3H 8H 4D) topcard=6D How do you search ${computerhand} for all elements containing either a "6" or a "D" then save the output to a file? This is a part of a Terminal game of Crazy 8's that I'm attempting to write in Bash. Any... (2 Replies)
Discussion started by: cogiz
2 Replies

5. Shell Programming and Scripting

Help reading the array and sum of the array elements

Hi All, need help with reading the array and sum of the array elements. given an array of integers of size N . You need to print the sum of the elements in the array, keeping in mind that some of those integers may be quite large. Input Format The first line of the input consists of an... (1 Reply)
Discussion started by: nishantrefound
1 Replies

6. Shell Programming and Scripting

Grouping array elements - possible?

I have a script which takes backup of some configuration files on my server. It does that by using an array which contains the complete path to the files to backup. It copys the files to a pre defined dir. Each "program" has it's own folder, ex. apache.conf is being copied to /predefined... (7 Replies)
Discussion started by: dnn
7 Replies

7. Shell Programming and Scripting

Removing elements from an array

Hi I have two arrays : @arcb= (450,625,720,645); @arca=(625,645); I need to remove the elements of @arca from elements of @arcb so that the content of @arcb will be (450,720). Can anyone sugget me how to perform this operation? The code I have used is this : my @arcb=... (3 Replies)
Discussion started by: rkrish
3 Replies

8. Shell Programming and Scripting

How can I print array elements as different columns in bash?

Hi Guys, I have an array which has numbers including blanks as follows: 1 26 66 4.77 -0.58 88 99 11 12 333 I want to print a group of three elements as a different column in a file as follows:(including blanks where there is missing elements) for.e.g. array element #7... (4 Replies)
Discussion started by: npatwardhan
4 Replies

9. UNIX for Dummies Questions & Answers

How can i read array elements dynamically in bash?

Hi friends how can we read array elements dynamically in bash shell? (1 Reply)
Discussion started by: haisubbu
1 Replies

10. UNIX for Advanced & Expert Users

Percent complete error while scanning RAID array during 5.0.6 load

Percent complete SCO 5.0.6 / No longer an issue (0 Replies)
Discussion started by: Henrys
0 Replies
Login or Register to Ask a Question