[루비,질문] 파일을 열때, 파일에 쓸때 중첨된 부분을 루프로 돌

yuni의 이미지

노가다를 피하고 싶습니다.

행렬로 이루어진 숫자배열을 가지고 1,11,21... 행은 sec0.inp
2,12,22... 행은 sec1.inp 이런 식으로 저장을 합니다.
밑에 보시면 겹치는 부분들이 많은데 이것들은 LOOP로 세련되게 할 수는 없을까요?

#!/usr/bin/ruby
fileIn=File.new("node.inp", "w")
fileSec0=File.new("sec0.inp", "w")    # 노가다 시작 
fileSec1=File.new("sec1.inp", "w")
fileSec2=File.new("sec2.inp", "w")
fileSec3=File.new("sec3.inp", "w")
fileSec4=File.new("sec4.inp", "w")
fileSec5=File.new("sec5.inp", "w")
fileSec6=File.new("sec6.inp", "w")
fileSec7=File.new("sec7.inp", "w")
fileSec8=File.new("sec8.inp", "w")
fileSec9=File.new("sec9.inp", "w")
lines =IO.readlines("point.inp")
data =[]
lines.each do |line|
  data << line.split
end

#To change negative x-dir for stern 
#To move (0,0,0) form turret to midship section 
a = -1.0
data_nega=[]
size = lines.length-1
i=0
lines.length.times do |i|
  
  data_nega[i] = data[i][0].to_f * a -112.0
#  puts data_nega[i].to_s
  data[i][0] = data_nega[i]
#  puts data[i]
  fileIn.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  if  i.to_i%10 ==0        #노가 다시 시작 
    fileSec0.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  elsif  i.to_i%10 ==1
    fileSec1.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  elsif  i.to_i%10 ==2
    fileSec2.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  elsif  i.to_i%10 ==3
    fileSec3.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  elsif  i.to_i%10 ==4
    fileSec4.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  elsif  i.to_i%10 ==5
    fileSec5.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  elsif  i.to_i%10 ==6
    fileSec6.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  elsif  i.to_i%10 ==7
    fileSec7.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  elsif  i.to_i%10 ==8
    fileSec8.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  elsif  i.to_i%10 ==9
    fileSec9.puts data[i][0].to_s + " " + data[i][1].to_s + "  " + data[i][2].to_s
  end
end

알려 주시면 감사하겠습니다.

Fe.head의 이미지

일단 File을 배열로 만들로 만들면 되겠네요.

C언어로 한다면

#define   MAX_ROW  10

FILE * file[MAX_ROW]];
char filename[256];

for(int i = 0 ; i<MAX_ROW; ++i)
{
    sprintf(filename, "sec%d.inc", i);
    file[i] = fopen(filename, "w");
}

....

int index = i%MAX_ROW;
fprintf(file[i],  "%d %d %d\n", data[i][0], data[i][1], data[i][2]);
...

고작 블로킹 하나, 고작 25점 중에 1점, 고작 부활동
"만약 그 순간이 온다면 그때가 네가 배구에 빠지는 순간이야"

nohmad의 이미지

조금 더 줄일 수도 있겠지만, 더 줄이면 알아보기 힘들 것 같아, 이 정도 선에서 멈추는 것이 좋을 것 같습니다.

# Perl + C++ style file handling

fr    = File.open('point.inp')
fnode = File.open('node.inp', 'w')
fsec  = (0..9).collect { |n| File.open("sec#{n}.inp", 'w') }

while fr.gets
  data = $_.split
  data[0] = data.first.to_f * -1.0 - 112.0
  write_data = data[0..2].join(' ') + $/
  fnode << write_data
  fsec[$. % 10] << write_data
end

이 소스에 대해 설명을 하면...

1) point.inp를 읽어서 각 라인을 공백으로 분리(data = $_.split)
2) 배열의 0번째 요소(data.first)를 꺼내 연산(data.first.to_f * -1.0 - 112.0)을 수행하고 그 결과를 번째 요소에 기록함.
3) 배열의 0번째에서 2번째 요소까지 공백을 넣어서 합친 문자열을 만듬. (write_data = data[0..2].join(' ') + $/)
4) 3)에서 만든 문자열을 node.inp에 쓰고, point.inp에서 읽은 각 라인을 0..9까지 로테이션하면서 sec[0-9].inp 파일에 기록.

몇가지 펄 스타일 매직 변수가 사용되었는데,

$_는 입력스트림을 버퍼 모드로 읽을 때의 바로 그 임시 버퍼의 값(line terminated string)입니다. $/는 C의 개행문자('\n')에 해당하며 플랫폼 고유의 값을 가집니다. $.는 버퍼 모드에서의 라인 번호를 가리킵니다.

* 간단한 파일 처리여서 자원 청소는 따로 하지 않았습니다.

yuni의 이미지

:) :)답변을 주신 fehead님, mohmad님께 감사 드립니다. :) :)
내용이 좋아서 출력해서 노트에 붙었습니다. <- 영구보관용.

==========================
부양가족은 많은데, 시절은 왜 이리 꿀꿀할까요?
=====================
"지금하는 일을 꼭 완수하자."

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.