到目前为止,这是for循环的片段。问题是减少空间变量
for i <- 0..(row-1) do
for j <- 0..(col-1) do
if j == 0 do
IO.write"+"
end
IO.write "--+"
end
IO.puts ""
columns= col+1
for columns <- 1..columns do
if columns == 1 do
IO.write "|"
end
if spaces < 10 do
IO.write " "
IO.write spaces
IO.write "|"
end
end
spaces = spaces - 1 <- This won't decrement after it goes through the forloop again!
end
end
我需要在Elixir中制作一个输出类似内容的棋盘游戏。
+---+---+---+
| 12| 11| 10|
|B | | |
+---+---+---+
| 7| 8| 9|
| a | S| e |
+---+---+---+
| 6| 5| 4|
| e | L|Ad |
+---+---+---+
| 1| 2| 3|
| | | |
+---+---+---+
我已经在java上使用以下代码在另一个for循环中使用for循环来完成它,但这在elixir上是不可能的。有什么想法如何处理这个?谢谢。
编辑:如果有人想看我的java代码,这里就是。
public class math {
static int col = 10;
static int row = 10;
static String top= "---+";
static String side= "|";
static int spaces=col*row;
static int columns;
static int dash;
static String player="A";
public static void main(String args[]){
for ( int i=0; i < row; i++ ){
for ( int j=0; j < col; j++ ){
if ( j==0) System.out.print("+");
System.out.print(top);
}
System.out.print("\n");
columns=col+1;
while( columns > 1){
if(columns == col+1){
System.out.print("|");
}
if( spaces < 10){
System.out.print(" "+spaces+"|");}
else if (spaces <100){
System.out.print(" "+spaces+"|");
}
else{
System.out.print(""+spaces+"|");
}
spaces--;
columns--;}
System.out.print("\n");
columns=col+1;
while(columns >1){
if (columns == col +1) {System.out.print("|");}
System.out.print(" |");
columns--;}
System.out.print("\n");
if( i == row-1){
int botside = col;
while(botside !=0){
if(botside == col){
System.out.print("+");
}
System.out.print(top);
botside--;}
}
}
}
答案 0 :(得分:1)
你可以使用for special form列表理解来实现你需要的东西:
for i <- 0..(row-1) do
for j <- 0..(col-1) do
# Rest of the code
end
end
答案 1 :(得分:0)
以下是我的解决方案 - 基于您填写数据的电路板模板。
defmodule Main do
def main( ) do
data =
[
"B ", " ", " ",
" a ", " S", " e ",
" e ", " L", "Ad ",
" ", " ", " ",
"" #required terminal
]
IO.puts print_board( data )
end
defp print_board( data ) do
board = """
+---+---+---+
| 12| 11| 10|
| | | |
+---+---+---+
| 7| 8| 9|
| | | |
+---+---+---+
| 6| 5| 4|
| | | |
+---+---+---+
| 1| 2| 3|
| | | |
+---+---+---+
"""
String.split( board," ") # Splits board string into a list of strings
|> Enum.zip( data ) # interleaves with data - as list of tuples
|> Enum.map( fn {a,b} -> a <> b end ) # maps tuples back to merge the list.
end
end
我的测试表明,当您运行Main.main